We convert the following sequence to dict type .
lst = [('a', 1), ('b', 2), ('c', 3)]
The common way of writing
for k, v in lst:
dic[k] = v
more pythonic Writing
Use dictionary derivation to quickly generate Dictionary .
{k: v for k, v in lst}
When specifying key When there is no , take value Set to 0.
The common way of writing
if key not in dct:
dct[key] = 0
pythonic Writing
dct[key] = dct.get(key, 0)
The common way of writing
dic = {'Python': 1, 'Java': 2}
new_dic = {}
for k, v in dic.items():
new_dic[v] = k
more pythonic Writing
dic = {'Python': 1, 'Java': 2}
new_dic = {v: k for k, v in dic.items()}
Example data
lst = [('a', 1), ('b', 2), ('c', 3)]
dic = {'a': [0]}
If we need to be based on lst To update dic Data in , When key There is , Will value Add to the end of the original sequence , Otherwise initialize value And save with sequence .
The common way of writing
for key, value in lst:
if key in dic:
dic[key].append(value)
else:
dic[key] = [value]
more pythonic Writing
for (key, value) in lst:
group = dic.setdefault(key, [])
group.append(value)
# dic:{'a': [0, 1], 'b': [2], 'c': [3]}
setdefault(key, default) Will judge first key Whether there is , To be is to return dct[key] , If it doesn't exist dct[key] Set to [] And back to .
If we need to get two dictionaries now key Mapping information of intersecting parts .
The common way of writing
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
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}
there dic1.keys() & dic2.keys() What we use is keys() Doing set operations ,items() Set operation can also be carried out .
If we want to get two dictionaries now key,value Identical parts
dic1 = {'Python': 1, 'Java': 2, 'C': 3}
dic2 = {'Python': 3, 'Java': 2, 'C++': 1}
print(dic1.items() & dic2.items())
# {('Java', 2)}
Flexible use of keys,items() Characteristics of set operation , It can quickly extract the content we want .
Use sorted() Function for fast implementation key or value Sort .
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(' Press the key in descending order :', {key: value for key, value in lst1})
print(' In descending order of values :', {key: value for key, value in lst2})
# Press the key in descending order : {'a': 2, 'b': 1, 'c': 3, 'd': 0}
# In descending order of values : {'d': 0, 'b': 1, 'a': 2, 'c': 3}
If a sequence contains more than one dictionary , Now continue sorting these dictionaries by criteria . It can also be used sorted() Function to implement .
dict_list = [
{'letter': 'B', 'number': '2'},
{'letter': 'A', 'number': '3'},
{'letter': 'B', 'number': '1'}
]
# Press letter Sort
print(sorted(dict_list,
key=lambda dic: dic['letter']))
# Press letter, number Sort
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() Words , The above code can be changed , Faster execution .
from operator import itemgetter
print(sorted(dict_list
key=itemgetter('letter')))
print(sorted(dict_list,
key=itemgetter('letter', 'number')))
itemgetter() The value obtained is not a value , It defines a function , This function acts on the target object .