Dictionary dict

whitehousechef·2024년 1월 9일
0

sorted()

I didnt know but sorted() can take any iterable - tuple, list AND yes a dictionary is included.

So you can sort the key and value as you like. For example, with lambda:

my_dict = {'apple': 3, 'banana': 1, 'orange': 2}

sorted_items = sorted(my_dict.items(), key=lambda x: (x[0], -x[1]))

for key, value in sorted_items:
    print(f'{key}: {value}')

ALso, just via sorting .items() sorts the keys. If u want sort via value, you use lambda like

sorted(tree.items(),key =lambda x:x[1]

What you CANT do

you cant use sort(). You must use sorted() i didnt know that in interview

from collections import defaultdict

# Step 2: Create and populate a defaultdict
my_defaultdict = defaultdict(int)
my_defaultdict['banana'] = 3
my_defaultdict['apple'] = 5
my_defaultdict['cherry'] = 2

# Step 3: Sort the defaultdict by keys
sorted_defaultdict = dict(sorted(my_defaultdict.items()))

# Step 4: Print the sorted dictionary
print(sorted_defaultdict)

0개의 댓글