Reputation: 31
I have to make a dictionary that will turn this list:
locations = [
['Lorraine Izaguirre', 'MA'],
['Chris Clements', 'PA'],
['Kari Bacon', 'PA'],
['Chris Clements', 'NY'],
['Chris Clements', 'NJ'],
['Jamee Cheek', 'PA'],
['Kari Bacon', 'NY']
]
into:
{'Lorraine Izaguirre': ['MA'], 'Chris Clements': ['PA', 'NY', 'NJ'], 'Kari Bacon': ['PA', 'NY'], 'Jamee Cheek': ['PA']}
This is the code I have already made, but for some reason I keep getting an error saying that I can't append a string to a list. I am very confused, because I thought I was explicitly stating that state
is a 1x1 list in the append statement. Any help would be appreciated.
def organize(locations):
name_dict = {}
for i in range(len(locations)-1):
name = locations[i][0]
state = locations[i][1]
if name not in name_dict:
name_dict.update({name:state})
else:
name_dict[name] = name_dict[name].append([state])
return name_dict
Edit: Solved it, there were a couple issues
1.) pointed out below that I needed to change name_dict.update({name:state})
into name_dict.update({name:[state]})
2.) I needed to change range(len(locations)-1)
into range(len(locations))
and 3.) change name_dict[name].append([state])
into name_dict[name].append(state)
Upvotes: 0
Views: 62
Reputation: 8437
collections.defaultdict
has been designed for this
from collections import defaultdict
def organize(locations):
name_dict = defaultdict(list)
for name, state in locations:
name_dict[name].append(state)
return name_dict
Upvotes: 0
Reputation: 195438
You can use dict.setdefault
for the task:
locations = [
["Lorraine Izaguirre", "MA"],
["Chris Clements", "PA"],
["Kari Bacon", "PA"],
["Chris Clements", "NY"],
["Chris Clements", "NJ"],
["Jamee Cheek", "PA"],
["Kari Bacon", "NY"],
]
out = {}
for l, abbr in locations:
out.setdefault(l, []).append(abbr)
print(out)
Prints:
{'Lorraine Izaguirre': ['MA'], 'Chris Clements': ['PA', 'NY', 'NJ'], 'Kari Bacon': ['PA', 'NY'], 'Jamee Cheek': ['PA']}
Upvotes: 2