Replace Key in Dictonary by another Dictonary and use loops Python3

Viewed 59

thanks for help.

1. i have input dict:

populations = {
    'US-AL': 4887871,
    'US-AK': 737438,
    'US-AZ': 7171646}

and i have another input dict with conformity USA states and Russia subject (this conformity doesn't matter, just like instance ) here it is "another" dict:

usa_rus = {
    'US-AL': 'RU-MOW',
    'US-AK': 'RU-KDA',
    'US-AZ': 'RU-SVE'}

2. My task is replace key in population dict. New key in population dict should be value from dict usa_rus. Another words, i want replace USA States in key to Russia subjects, value in dict population not changed.

what i want in output:

populations_new = {
    'RU-MOW': 4887871,
    'RU-KDA': 737438,
    'RU-SVE': 7171646}

3.Unfortunately, i haven't deep knowledge in python and creating dictionary, i'm studying. I use only one solution but it is not clear:

list = []

for keys,values in populations.items():
    list.append({usa_rus[keys]:values})

output:

[{'RU-MOW': 4887871}, {'RU-KRS': 737438}, {'RU-SVE': 7171646}]

Please help me to make output which i want :)

4 Answers

First, you shouldn't use Python reserved names as variable names, so rename your list variable.

Then, you want to use the dict to get the output to match your desired output. With minor changes to your code:

new_dict = dict()  # Or new_dict = {}
for key, value in usa_rus.items():
    new_dict[value] = populations[key]
def convert(populations, usa_rus):
    result = {}
    for key, value in populations.items():
        if key in usa_rus.keys():
            result[usa_rus[key]] = value
        else:
            result[key] = value
    return result
    
populations = {
    'US-AL': 4887871,
    'US-AK': 737438,
    'US-AZ': 7171646}
usa_rus = {
    'US-AL': 'RU-MOW',
    'US-AK': 'RU-KDA',
    'US-AZ': 'RU-SVE'}

convert(populations, usa_rus)
print (populations)

Output:

{'RU-MOW': 4887871, 'RU-KDA': 737438, 'RU-SVE': 7171646}
for k, v in usa_rus.items():     
    if k in populations:
        populations[v] = populations.pop(k)

It's easier if you reverse the usa_rus dictionary:

>>> rus_usa = {r: u for u, r in usa_rus.items()}
>>> populations_new = {r: populations[rus_usa[r]] for r in rus_usa.keys()}
>>> populations_new
{'RU-MOW': 4887871, 'RU-KDA': 737438, 'RU-SVE': 7171646}
Related