Reputation: 137
I have a dictionary:
d = {'name': ['sarah', 'emily', 'brett'], 'location': ['LA', 'NY', 'Texas']}
I also have a list:
l = ['name', 'location']
I want to replace 'name' in the list l
with the list ['sarah', 'emily', 'brett']
in dictionary d
(same thing for location).
So the outcome would be:
l = ['sarah', 'emily', 'brett', 'LA', 'NY', 'Texas']
for item in l:
l.append(d[item])
l.remove(item)
this is what I did and I got a type error, unhashable type: 'list'. what should I do to fix this?
Upvotes: 1
Views: 2975
Reputation: 3393
In my case, the item in list only partial shown in dictionary. To avoid error I used:
[y for x in l for y in d.get(x,[x])]
When test data changed like:
l = ['name', 'location', 'test']
The result would like below:
print([y for x in l for y in d.get(x,[x])])
>>> ['sarah', 'emily', 'brett', 'LA', 'NY', 'Texas', 'test']
Upvotes: 0
Reputation: 317
replace .append() with .extend()
tmp = []
for i in l:
tmp.extend(d[i])
l = tmp
Upvotes: 0
Reputation: 26698
Don't change list when you are looping in, because iterator will not be informed of your changes.
To replace them, just generate a new one containing d
lists selected with l
items.
[d[item] for item in l]
If you are not sure that all items in l
are keys in d
you can add test before trying to get from d
:
[d[item] for item in l if d.has_key(item)]
Upvotes: 0
Reputation: 3954
You should not change the list inside the loop if you are iterating in the items of that list.
Try creating a new one and then rename it. The garbage collector will take care of old version of l
.
new_l = []
for item in l:
new_l.extend(d[item])
l = new_l
Upvotes: 1
Reputation: 24052
The simplest solution is to create a new list:
l = [y for x in l for y in d[x]]
The results are the flattened substituted items:
print l
>>> ['sarah', 'emily', 'brett', 'LA', 'NY', 'Texas']
Upvotes: 1