python 常用技巧 — 字典 (dictionary)

目录:

1. python 相加字典所有的键值 (python sum all values in dictionary)

2. python 两个列表分别组成字典的键和值 (python two list serve as key and value for dictionary)

3. python 把字典所有的键值组合到一个列表中 (python get dictionary values to combine a list)

4. python 使用一行代码打印字典键值对 (python print dictionary key-value pairs with one line of code)

5. python 嵌套字典中相加所有指定键的所有值 (python sum values for each key in nested dictionary)

内容:

1. python 相加字典所有的键值 (python sum all values in dictionary)

https://stackoverflow.com/questions/4880960/how-to-sum-all-the-values-in-a-dictionary

d = {'a':1, 'b':2, 'c':4}
sum(d.values())
7

 

2. python 两个列表分别组成字典的键和值 (python two list serve as key and value for dictionary)

https://stackoverflow.com/questions/209840/convert-two-lists-into-a-dictionary

In [1]: layout_type = ['LTTextBox', 'LTFigure', 'LTImage', 'LTLine', 'LTRect']

In [2]: color = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (160, 32, 240)]

In [3]: draw_color = dict(zip(layout_type, color))

In [4]: draw_color
Out[4]: 
{'LTFigure': (0, 255, 0), 'LTImage': (0, 0, 255), 'LTLine': (255, 255, 0), 'LTRect': (160, 32, 240), 'LTTextBox': (255, 0, 0)}

3. python 把字典所有的键值组合到一个列表中 (python get dictionary values to combine a list)

https://thispointer.com/python-how-to-create-a-list-of-all-the-values-in-a-dictionary/

In [205]: a = {'apple':2, 'banana':3, 'pear':5}

In [206]: a
Out[206]: {'apple': 2, 'banana': 3, 'pear': 5}

In [207]: list(a.values())
Out[207]: [2, 3, 5]

  

4.  python 使用一行代码打印字典键值对 (python print dictionary key-value pairs with one line of code)

 https://thispointer.com/python-4-ways-to-print-items-of-a-dictionary-line-by-line/

In [3]: student_score = {'Ritika': 5, 'Sam': 7, 'John': 10, 'Aadi': 8}          

In [4]: [print(key, " : ", value) for key, value in student_score.items()]      
Ritika  :  5
Sam  :  7
John  :  10
Aadi  :  8
Out[4]: [None, None, None, None]

5. python 嵌套字典中相加所有指定键的所有值 (python sum values for each key in nested dictionary)  

 https://www.geeksforgeeks.org/python-sum-values-for-each-key-in-nested-dictionary/

In [42]: [m for m in range(len(a)) if a[m]=="的"]                               
Out[42]: [18]


In [43]: a = {1: {'index_answer': [18], 'num_answer': 1}, 2:{'index_answer': [4]
    ...: , 'num_answer': 7}}                                                    

In [44]: a                                                                      
Out[44]: 
{1: {'index_answer': [18], 'num_answer': 1},
 2: {'index_answer': [4], 'num_answer': 7}}

In [45]: sum(m["num_answer"] for m in a.values())                               
Out[45]: 8

 

原文地址:https://www.cnblogs.com/ttweixiao-IT-program/p/11905348.html