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

时间:2018-11-29 15:34:56

标签: python python-3.x dictionary

我需要使用两个以前创建的字典返回给定id号的值列表,其中需要的值存储在字典中。

我创建的两个词典如下:

{100: ('Mulan', [300, 500], [200, 400]), 
200: ('Ariel', [100, 500], [500]), 
300: ('Jasmine', [500], [500, 100]), 
400: ('Elsa', [100, 500], []), 
500: ('Belle', [200, 300], [100, 200, 300, 400])}

{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])}

第一个字典的格式为{id:((name,followers,following}}。

第二个词典的格式为{key:(id,chirp,tags,likes,dislikes}。

对于给定的ID号100, 200, 300, 400, 500,我需要为他们关注的每个用户返回最喜欢的chi声。

例如ID号为500的输出示例为:

['Make the ocean great again.', 
'If some random dude offers to %ShowYouTheWorld do yourself a favour and %JustSayNo.', 
'Does not want to build a %SnowMan %StopAsking']

我了解这里需要进行的过程,但是我需要一些帮助,以获取如何在一个字典中找到所需值,然后在第二个字典中搜索所需值的功能。

非常感谢您提供的任何指导!

1 个答案:

答案 0 :(得分:0)

您需要使用嵌套循环从第一个字典开始遍历两个字典:

user_input = 500

for key, value in dictionary1.items():
if user_input == key:
    for key2, value2 in dictionary2.items():
        for items in value[1]:  
            if items == value2[0]:
                print(value2[1])

key = id

value [1] [0] =名称

value [1] [1] =关注者

value [1] [2] =关注

key2 =键

value2 [0] = id

value2 [1] = rp

value2 [2] =标签

value2 [3] =喜欢

value2 [4] =不喜欢