迭代一系列词典

时间:2017-09-20 16:52:27

标签: python list dictionary for-loop

在以下简单问题上会有所帮助。如何迭代字典列表?我只需要每个字典的键。 EG:

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

我需要在以下列表中添加密钥tweet_list

以下代码有什么问题?对基本问题道歉,但主要是列表的数据结构导致了我的麻烦。

EG:

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

2 个答案:

答案 0 :(得分:2)

请注意Python 2和3中的不同选项:

<强>代码

[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

中间选项利用dictionary views而不是列表。最后一个选项是大多数Pythonic(@Yaroslav Surzhikov建议)。

<强>计时

通过%timeit -n 100000确认Python 3(尽可能):

  1. 6.58μs:[list(d.keys())[0] for d in list_]
  2. 3.23μs:[d.keys()[0] for d in list_]
  3. 3.97μs:[next(iter(d.viewkeys())) for d in list_]
  4. 4.52μs:[next(iter(d.keys())) for d in list_]
  5. 1.75μs:[key for d in list_ for key in d]
  6. @Yaroslav Surzhikov的贡献

答案 1 :(得分:0)

你想要这个列表理解:

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