简体   繁体   English

嵌套字典理解

[英]Nested dict comprehension

In the following code, 在以下代码中,

[{word: score_tweet(tweet) for word in tweet} for tweet in tweets]

I am getting a list of dicts: 我得到的字典列表:

[{u'soad': 0.0, u'<3': 0.0}, {u'outros': 0.0, u'acredita': 0.0}]

I would like to obtain only one flat dict like: 我只想获得一个简单的字典,例如:

{u'soad': 0.0, u'<3': 0.0, u'outros': 0.0, u'acredita': 0.0}

How should I change my code? 我应该如何更改我的代码? Note: I am using Python 2.7. 注意:我正在使用Python 2.7。

{word: score_tweet(tweet) for tweet in tweets for word in tweet}

Move the for loop into the dict comprehension: for循环移至dict理解中:

{word: score_tweet(tweet) for tweet in tweets for word in tweet}

Keep in mind that two for loops in one line are hard to read. 请记住,一行中的两个for循环很难阅读。 I would do something like this instead: 我会做这样的事情:

scores = {}

for tweet in tweets:
    tweet_score = score_tweet(tweet)

    for word in tweet:
        scores[word] = tweet_score

You need an intermediary step. 您需要一个中间步骤。

words = []
tweets = ["one two", "three four"]
for tweet in tweets:
    words.extend(tweet.split())
scores = {word: score_tweet(word) for word in words}
"""
[{u'soad': 0.0, u'<3': 0.0}, {u'outros': 0.0, u'acredita': 0.0}] 
->
{u'soad': 0.0, u'<3': 0.0, u'outros': 0.0, u'acredita': 0.0}
"""
tweets_merged = {}
tweets = [{u'soad': 0.0, u'<3': 0.0}, {u'outros': 0.0, u'acredita': 0.0}]
for tweet in tweets:    
    tweets_merged = dict(tweets_merged.items() + tweet.items())
print tweets_merged

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

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