Извлечение данных из вложенных словарей в цикле - PullRequest
0 голосов
/ 10 июля 2019

Учитывая словарь, 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 ]

2 голосов
/ 10 июля 2019
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 голосов
/ 10 июля 2019

Вы должны добавить nested_d[nested][country], чтобы получить значения.

0 голосов
/ 10 июля 2019
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)
0 голосов
/ 10 июля 2019

Вы можете попробовать это: -

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)

Я надеюсь, что это может помочь вам

0 голосов
/ 10 июля 2019

Вы также можете попробовать это:

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]
0 голосов
/ 10 июля 2019

Заменить цикл на:

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

print(US_count)

Выход:

[36, 46, 35]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...