1

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?

6 Answers 6

1

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']
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Tip: use new_l.extend() to get OP's expect output.
0

Use this code:

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

Comments

0

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)]

Comments

0

replace .append() with .extend()

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

Comments

0

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.