hello
hello

Reputation: 137

python: replace item in a list with items in a another list

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

Answers (6)

Jesse
Jesse

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

WendellLiu
WendellLiu

Reputation: 317

replace .append() with .extend()

tmp = []
for i in l:
    tmp.extend(d[i])
l = tmp

Upvotes: 0

Kenly
Kenly

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

centum
centum

Reputation: 131

Use this code:

l = [d.get(k, k) for k in l]

Upvotes: 0

eguaio
eguaio

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

Tom Karzes
Tom Karzes

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

Related Questions