在以下简单问题上会有所帮助。如何迭代字典列表?我只需要每个字典的键。 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)
答案 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(尽可能):
[list(d.keys())[0] for d in list_]
[d.keys()[0] for d in list_]
[next(iter(d.viewkeys())) for d in list_]
[next(iter(d.keys())) for d in list_]
[key for d in list_ for key in d]
@Yaroslav Surzhikov的贡献
答案 1 :(得分:0)
你想要这个列表理解:
>>> [list(d.keys())[0] for d in list_]
['negative', 'negative', 'positive', 'negative', 'negative', 'negative', 'positive']