简体   繁体   English

遍历字典列表

[英]Iterating through a list of dictionaries

Would love some help on the following simple question. 希望在以下简单问题上有所帮助。 How can I iterate through a list of dictionaries? 如何遍历词典列表? I would only need the keys of each dictionary. 我只需要每个字典的键。 EG: 例如:

list_ = [{'negative': 'sad'}, {'negative': 'missed'},
         {'positive': 'already :D'},{'negative': 'cry'}, 
         {'negative': 'cheating'}, {'negative': 'worry'},
         {'positive': 'Chilling'},]

I would need to append the keys in the following list tweet_list 我需要将密钥添加到以下列表中tweet_list

What is wrong with the following code? 以下代码有什么问题? Apologies for the basic question, but it's mainly the data structure of the list_ that is causing me troubles. 道歉是一个基本问题,但主要是list_的数据结构给我带来了麻烦。

EG: 例如:

for key in list_():
    append.tweet_list(key[0])
    print(tweet_list)

Note the different options in Python 2 and 3: 请注意Python 2和3中的不同选项:

Code

[d.keys()[0] for d in list_]                               # python 2

[next(iter(d.viewkeys())) for d in list_]                  # python 2

[next(iter(d.keys())) for d in list_]                      # python 2/3

[k for d in list_ for k in d]                              # python 2/3

The middle options leverage dictionary views as opposed to lists. 中间选项利用字典视图而不是列表。 The last option is most Pythonic (suggested by @Yaroslav Surzhikov). 最后一个选项是大多数Python语言(由@Yaroslav Surzhikov建议)。


Timings 计时

Confirmed in Python 3 (wherever possible) via %timeit -n 100000 : 在Python 3中通过%timeit -n 100000

  1. 6.58 µs: [list(d.keys())[0] for d in list_] 6.58 µs: [list(d.keys())[0] for d in list_]
  2. 3.23 µs: [d.keys()[0] for d in list_] 3.23 µs: [d.keys()[0] for d in list_]
  3. 3.97 µs: [next(iter(d.viewkeys())) for d in list_] 3.97 µs: [next(iter(d.viewkeys())) for d in list_]
  4. 4.52 µs: [next(iter(d.keys())) for d in list_] 4.52 µs: [next(iter(d.keys())) for d in list_]
  5. 1.75 µs: [key for d in list_ for key in d] 1.75 µs: [key for d in list_ for key in d]

Contribution by @Yaroslav Surzhikov @Yaroslav Surzhikov的贡献

You want this list comprehension: 您需要以下列表理解:

>>> [list(d.keys())[0] for d in list_]
['negative', 'negative', 'positive', 'negative', 'negative', 'negative', 'positive']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM