Home > Article > Backend Development > Python Dictionary: Is there any advanced gameplay that I don’t know how to do?
We convert the following sequence into dict type.
lst = [('a', 1), ('b', 2), ('c', 3)]
Common writing method
for k, v in lst: dic[k] = v
More pythonic writing method
Use dictionary derivation to quickly generate a dictionary.
{k: v for k, v in lst}
When the specified key does not exist, set the value to 0.
Ordinary writing method
if key not in dct: dct[key] = 0
pythonic writing method
dct[key] = dct.get(key, 0)
Ordinary writing method
dic = {'Python': 1, 'Java': 2} new_dic = {} for k, v in dic.items(): new_dic[v] = k
More pythonic writing method
dic = {'Python': 1, 'Java': 2} new_dic = {v: k for k, v in dic.items()}
Sample data
lst = [('a', 1), ('b', 2), ('c', 3)] dic = {'a': [0]}
If we need to update the data in dic based on lst, when the key exists, the value will be added to the end of the original sequence , otherwise initialize value and save it in sequence.
Ordinary writing method
for key, value in lst: if key in dic: dic[key].append(value) else: dic[key] = [value]
More pythonic writing method
for (key, value) in lst: group = dic.setdefault(key, []) group.append(value) # dic:{'a': [0, 1], 'b': [2], 'c': [3]}
setdefault(key, default) will first determine whether the key exists. If it exists, it will return dct[key], if it does not exist, it will return Then set dct[key] to [] and return.
If we now need to obtain the mapping information of the intersection of the keys of two dictionaries.
Ordinary writing method
dic1 = {'Python': 1, 'Java': 2, 'C': 3} dic2 = {'Python': 3, 'Java': 2, 'C++': 1} new_dic = {} for k, v in dic1.items(): if k in dic2.keys(): new_dic[k] = v print(new_dic) # {'Python': 1, 'Java': 2}
More pythonic writing method
dic1 = {'Python': 1, 'Java': 2, 'C': 3} dic2 = {'Python': 3, 'Java': 2, 'C++': 1} print({k: dic1[k] for k in dic1.keys() & dic2.keys()}) # {'Python': 1, 'Java': 2}
The dic1.keys() & dic2.keys() here use keys() for set operations , items() can also perform set operations.
If we now want to obtain the same key and value parts in two dictionaries
dic1 = {'Python': 1, 'Java': 2, 'C': 3} dic2 = {'Python': 3, 'Java': 2, 'C++': 1} print(dic1.items() & dic2.items()) # {('Java', 2)}
Flexibly use the characteristics of keys and items() set operations to quickly extract the content we want.
Use the sorted() function to quickly sort the key or value.
dic = {'a': 2, 'b': 1, 'c': 3, 'd': 0} lst1 = sorted(dic.items(), key=lambda x: x[0], reverse=False) # [('a', 2), ('b', 1), ('c', 3), ('d', 0)] lst2 = sorted(dic.items(), key=lambda x: x[1], reverse=False) # [('d', 0), ('b', 1), ('a', 2), ('c', 3)] print('按照键降序:', {key: value for key, value in lst1}) print('按照值降序:', {key: value for key, value in lst2}) # 按照键降序: {'a': 2, 'b': 1, 'c': 3, 'd': 0} # 按照值降序: {'d': 0, 'b': 1, 'a': 2, 'c': 3}
If a sequence contains multiple dictionaries, these dictionaries must now be sorted according to conditions. This can also be achieved using the sorted() function.
dict_list = [ {'letter': 'B', 'number': '2'}, {'letter': 'A', 'number': '3'}, {'letter': 'B', 'number': '1'} ] # 按 letter 排序 print(sorted(dict_list, key=lambda dic: dic['letter'])) # 按 letter, number 排序 print(sorted(dict_list, key=lambda dic: (dic['letter'], dic['number']))) # [{'letter': 'A', 'number': '3'}, {'letter': 'B', 'number': '2'}, {'letter': 'B', 'number': '1'}] # [{'letter': 'A', 'number': '3'}, {'letter': 'B', 'number': '1'}, {'letter': 'B', 'number': '2'}]
Of course, if you know itemgetter(), the above code can be changed and the execution speed will be faster.
from operator import itemgetter print(sorted(dict_list key=itemgetter('letter'))) print(sorted(dict_list, key=itemgetter('letter', 'number')))
itemgetter() does not obtain a value, but defines a function through which it is applied to the target object.
The above is the detailed content of Python Dictionary: Is there any advanced gameplay that I don’t know how to do?. For more information, please follow other related articles on the PHP Chinese website!