I often forget about it when I say AtCoder etc., but I wrote it myself because there were few sites that were unexpectedly organized.
Common guy
d = {}
#Or
d = dict()
Both behaviors differ depending on the presence or absence of existing keys
d['key'] = 'value'
#Compile error if the specified key does not exist
#Update existing value if the specified key already exists
d.setdefault('key', 'value')
#If the specified key does not exist, add a new element
#No change if the specified key already exists
As written below
d1 = {'key1': 'value1', 'key2': 'value2'}
d2 = {'key3': 'value3', 'key4': 'value4'}
d1.update(d2)
print(d1)
#{'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}
Since it returns in a mysterious format, it is necessary to convert it to list type with list comprehension notation or map
d = {'key1': 'value1', 'key2': 'value2'}
[i for i in d.keys()] #['key1', 'key2']
[i for i in d.values()] #['value1', 'value2']
I'm sleepy
Recommended Posts