0

I am trying to use the following dictionary ('ContinentDict') to bin countries by continent.

Thus, I would like to bin keys by value.

ContinentDict  = {'China':'Asia', 
                  'United States':'North America', 
                  'Japan':'Asia', 
                  'United Kingdom':'Europe', 
                  'Russian Federation':'Europe', 
                  'Canada':'North America', 
                  'Germany':'Europe', 
                  'India':'Asia',
                  'France':'Europe', 
                  'South Korea':'Asia', 
                  'Italy':'Europe', 
                  'Spain':'Europe', 
                  'Iran':'Asia',
                  'Australia':'Australia', 
                  'Brazil':'South America'}

When I try option 1:

v = {}

for key, value in sorted(d.items()):
    v.setdefault(value, []).append(key)

I get the error:

Traceback (most recent call last):
  File "<input>", line 2, in <module>
TypeError:'dict' object is not callable

When I try option 2:

from collections import defaultdict

dictionary = defaultdict(list)
for key, value in ContinentDict:
dictionary[value].append(key)

I get the error:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: first argument must be callable or None

Could anybody give me a helping hand?

Caledonian26
  • 727
  • 1
  • 10
  • 27

1 Answers1

4

For option 2, I think you missed .items(). This worked for me:

ContinentDict  = {'China':'Asia', 
                  'United States':'North America', 
                  'Japan':'Asia', 
                  'United Kingdom':'Europe', 
                  'Russian Federation':'Europe', 
                  'Canada':'North America', 
                  'Germany':'Europe', 
                  'India':'Asia',
                  'France':'Europe', 
                  'South Korea':'Asia', 
                  'Italy':'Europe', 
                  'Spain':'Europe', 
                  'Iran':'Asia',
                  'Australia':'Australia', 
                  'Brazil':'South America'}


dictionary = defaultdict(list)
for key, value in ContinentDict.items():
    dictionary[value].append(key)

print(dictionary)

Output:

defaultdict(<class 'list'>, {'Asia': ['China', 'Japan', 'India', 'South Korea', 'Iran'], 'North America': ['United States', 'Canada'], 'Europe': ['United Kingdom', 'Russian Federation', 'Germany', 'France', 'Italy', 'Spain'], 'Australia': ['Australia'], 'South America': ['Brazil']})
Anshul
  • 1,413
  • 2
  • 6
  • 14
  • @Anshul, this line: dictionary = defaultdict(list) is still giving me the error; TypeError: first argument must be callable or None – Caledonian26 May 14 '20 at 21:44
  • @Caledonian26 - Not sure y. Can you check this post: https://stackoverflow.com/questions/42137849/defaultdict-first-argument-must-be-callable-or-none. It might be of help – Anshul May 15 '20 at 03:15
  • @Anshul yes I've figured it out now! Thanks so much! – Caledonian26 May 15 '20 at 09:08