简体   繁体   中英

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.

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

Move the for loop into the dict comprehension:

{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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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