如何从字典中返回值列表?

时间:2018-11-29 21:29:45

标签: python python-3.x dictionary

我创建了一个像这样的字典:

{100000: (400, 'Does not want to build a %SnowMan %StopAsking', ['SnowMan', 'StopAsking'], [100, 200, 300], [400, 500]), 
100001: (200, 'Make the ocean great again.', [''], [], [400]), 
100002: (500, "Help I'm being held captive by a beast!  %OhNoes", ['OhNoes'], [400], [100, 200, 300]), 
100003: (500, "Actually nm. This isn't so bad lolz :P %StockholmeSyndrome", ['StockholmeSyndrome'], [400, 100], []), 
100004: (300, 'If some random dude offers to %ShowYouTheWorld do yourself a favour and %JustSayNo.', ['ShowYouTheWorld', 'JustSayNo'], [500, 200], [400]), 
100005: (400, 'LOLZ BELLE.  %StockholmeSyndrome  %SnowMan', ['StockholmeSyndrome', 'SnowMan'], [], [200, 300, 100, 500])}

我正在尝试返回包含给定标记的字符串列表,其中我的字典的格式为{string_id: (user_id, string, tags, likes, dislikes)}

到目前为止,我的代码如下:

for key, value in mydict.items():
    for items in value:
        if items == value[2]:
            tagged_chirps = [value[1]]
return tagged_chirps

但是,当我为“ SnowMan”标记运行此函数时,该函数仅返回:

['LOLZ BELLE.  %StockholmeSyndrome  %SnowMan']

不是我希望它返回的内容,而是:

['Does not want to build a %SnowMan %StopAsking', 
    'LOLZ BELLE.  %StockholmeSyndrome  %SnowMan']

有人知道为什么我的函数只会返回一个字符串而不是所有所需的字符串吗?

4 个答案:

答案 0 :(得分:0)

这适用于您的字典:

def get_string(dict,tag):
    result=[]
    for el in mydisct:
        if tag in mydisct[el][2]:
            result.append(mydisct[el][1])
    return result

print get_string(mydisct,'SnowMan')

答案 1 :(得分:0)

要生成列表,您需要创建一个列表,然后添加到列表中。

tagged_chirps=[]
for key, value in mydict.items():
    if 'SnowMan' in value[2]:
        tagged_chirps += [value[1]]
print(tagged_chirps)

答案 2 :(得分:0)

只需使用列表推导即可构建您的字符串列表:

tag = 'SnowMan'

strings = [v[1] for k,v in my_dict.items() if tag in v[2]]

返回:

['Does not want to build a %SnowMan %StopAsking', 'LOLZ BELLE.  %StockholmeSyndrome  %SnowMan']

答案 3 :(得分:0)

您可以尝试以下方法:

tag = 'SnowMan'
res = [string for user_id, string, tags, likes, dislikes in my_dict.values() if tag in tags]

返回:

['Does not want to build a %SnowMan %StopAsking', 'LOLZ BELLE.  %StockholmeSyndrome  %SnowMan']