简体   繁体   中英

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?

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

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

使用此代码:

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

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

replace .append() with .extend()

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM