Sarkar B
Sarkar B

Reputation: 1

Assign values to existing dictionary keys as the dictionary is being made using dictionary comprehension

Python: Write a function named big_countries that:

Input

country_info = {'Afghanistan': ['Asia', 652230, 25500100, 20343000, True],
'Albania': ['Europe', 28748, 2831741, 12960000, False],
'Algeria': ['Africa', 2381741, 37100000, 188681000, True],
'Andorra': ['Europe', 468, 78115, 3712000, False],
'Angola': ['Africa', 1246700, 20609294, 100990000, True]}

I have written the following code which works perfectly fine at doing the said task.

filtered_dict = dict()
for (k,v) in country_info.items():
    if v[4]: filtered_dict[v[0]] = filtered_dict.get(v[0], []) + [k]
print(filtered_dict)

Expected Output:

{'Asia': ['Afghanistan'], 'Africa': ['Algeria', 'Angola']}

But I get an itchy feeling that this can be shortened into something like:

filtered_dict = {v[0] : filtered_dict.get(v[0], []) + [k] for (k,v) in country_info.items() if v[4]}

The problem is that 1) I am dumb, 2) The filtered_dict.get() cannot access a dictionary before it is made or in other words we have not defined filtered_dict yet.

I can do something like:

temp_dict = dict()
filtered_dict = {v[0] : temp_dict.get(v[0], []) + [k] for (k,v) in country_info.items() if v[4]}

#Output 
{'Asia': ['Afghanistan'], 'Africa': ['Angola']}

But the country names get overwritten each time the same continent occurs. I want the country names to be appended not overwritten.

Can anyone help me write a shorter version of the working code possibly using recursion. Thanks!

Upvotes: 0

Views: 46

Answers (2)

Bartosz Karwacki
Bartosz Karwacki

Reputation: 331

country_info = {'Afghanistan': ['Asia', 652230, 25500100, 20343000, True],
'Albania': ['Europe', 28748, 2831741, 12960000, False],
'Algeria': ['Africa', 2381741, 37100000, 188681000, True],
'Andorra': ['Europe', 468, 78115, 3712000, False],
'Angola': ['Africa', 1246700, 20609294, 100990000, True]}

def big_countries(country_info: dict) -> dict:
    filtered_dict = {}
    for k,v in  country_info.items():
        if v[4]:
            filtered_dict.setdefault(v[0], [])
            filtered_dict[v[0]].append(k)
    return filtered_dict


print(big_countries(country_info))

output

{'Asia': ['Afghanistan'], 'Africa': ['Algeria', 'Angola']}

Upvotes: 0

user2390182
user2390182

Reputation: 73470

You can certainly simplify what you have:

filtered_dict = {}
for k, (x, *_, y) in country_info.items():
    if y: 
        filtered_dict.setdefault(x, []).append(k)

Upvotes: 1

Related Questions