程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python Dictionary: is there a higher-level game I cant play?

編輯:Python

Generate dictionary from sequence

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}

key The default value of

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)

In exchange for key And value

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()}

Sequence modification and initialization

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 .

key,items Set operation of

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 .

Press key or value Sort dictionaries

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}

Sorting multiple dictionaries

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved