[Coding test] 6. Dictionary dict

whitehousechef·2024년 1월 9일

adding or overriding key-value pair

So even if we try to add a non-existing key or override an existing key, we can just do

result[key] = value  # overwrite or add new key

KeyError will only occur if we try to access a dictionary key that DOESNT EXIST.

update()

merges another dictionary to the current dict

d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 4}

d1.update(d2)
print(d1)  # {'a': 1, 'b': 3, 'c': 4}

sorted()

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

So you can sort the key and value as you like. For example, with lambda: so key value is in a tuple.

https://velog.io/@whitehousechef/Neetcode-Group-Anagrams

Cuz we cant sort based on the values of dictionary just via dictionary. So we first have to convert the items or values into list via sorted() and then use key=lambda x to sort based on key x[0] or val x[1].

If u wanna convert it back to dictionary format via dict() (cuz sorted returns a list), you should do sorted_items = dict(sorted(my_dict.items(), key=lambda x: (x[0], -x[1]))).

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 this and call .items()!!. Just doing sorted(dic) wont work cuz x[1] will then be the second cahracter of the key

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

get first element in dictionary

my_dict = {'a': 1, 'b': 2, 'c': 3}
first_key = next(iter(my_dict))
print(first_key)  # 'a'

first_pair = next(iter(my_dict.items()))
print(first_pair)  # ('a', 1)

first_value = next(iter(my_dict.values()))
print(first_value)  # 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개의 댓글