循环从嵌套字典中提取数据

时间:2019-07-10 05:45:35

标签: python data-structures

  

给出字典nested_d,将字典中所有三届奥运会的美国奖牌计数保存到列表US_count

nested_d = {'Beijing':{'China':51, 'USA':36, 'Russia':22, 'Great Britain':19}, 'London':{'USA':46, 'China':38, 'Great Britain':29, 'Russia':22}, 'Rio':{'USA':35, 'Great Britain':22, 'China':20, 'Germany':13}}
US_count = []

for nested in nested_d:
    # print(nested)
    for country in nested_d[nested]:
            if "USA" in country:
                    US_count.append(country)

print(US_count)

我希望输出为[35,36,46],但实际输出为['USA', 'USA', 'USA'] 请帮我解决这个问题

6 个答案:

答案 0 :(得分:2)

您应该附加nested_d[nested][country]来获取值。

答案 1 :(得分:2)

nested_d = {'Beijing':{'China':51, 'USA':36, 'Russia':22, 'Great Britain':19}, 'London':{'USA':46, 'China':38, 'Great Britain':29, 'Russia':22}, 'Rio':{'USA':35, 'Great Britain':22, 'China':20, 'Germany':13}}

res = [nested_d[host]['USA'] for host in nested_d]

print(res)

输出

[36, 46, 35]

答案 2 :(得分:0)

将循环替换为:

x

输出:

testProperty "diffProcResult" $
   \(t::TestIt Identity) ->
     let (MyFun f) = y t
         yVal = f $ x t
     in ...

答案 3 :(得分:0)

您也可以尝试以下方法:

nested_d = {'Beijing':{'China':51, 'USA':36, 'Russia':22, 'Great Britain':19}, 'London':{'USA':46, 'China':38, 'Great Britain':29, 'Russia':22}, 'Rio':{'USA':35, 'Great Britain':22, 'China':20, 'Germany':13}}
US_count = []

for nested in nested_d:
    for country in nested_d[nested]:
            if country=="USA":
                    US_count.append(nested_d[nested][country])

print(US_count)

输出:

[35, 36, 46]

答案 4 :(得分:0)

您可以尝试以下操作:-

nested_d = {'Beijing':{'China':51, 'USA':36, 'Russia':22, 'Great Britain':19}, 'London':{'USA':46, 'China':38, 'Great Britain':29, 'Russia':22}, 'Rio':{'USA':35, 'Great Britain':22, 'China':20, 'Germany':13}}

US_count = []



for nested in nested_d:
    for country,medal in nested_d[nested].items() :
        if country == 'USA':
            US_count.append(medal)

print(US_count)

输出

[36, 46, 35]

OR 您可以尝试以下操作:-

us_count = []

for key, value in nested_d.items():  #Here we getting dictionary in value.
    if 'USA' in value.keys():
        us_count.append(value['USA'])

print(us_count)

希望对您有帮助

答案 5 :(得分:0)

You just need to iterate through the nested dict and get the value of key USA.

nested_d = {
            'Beijing':{
                'China':51,
                'USA':36,
                'Russia':22,
                'Great Britain':19
            },
            'London':{
                    'USA':46,
                    'China':38,
                    'Great Britain':29,
                    'Russia':22
            },
            'Rio':{
                'USA':35,
                'Great Britain':22,
                'China':20,
                'Germany':13
            }
}

us_medals_count = []

for key, value in nested_d.items():
    if 'USA' in value.keys():
        us_medals_count.append(value['USA'])

print(us_medals_count)