user1566200
user1566200

Reputation: 1838

Replace values in nested list with dict in Python?

I have a nested list:

my_list = ['a','b','c','dog', ['pig','cat'], 'd']

and a dict:

my_dict = {'dog':'c','pig':'a','cat':'d'}

I would like to use the dict, such that I get a list:

new_list = ['a', 'b', 'c', 'c', ['a', 'd'], 'd']

I've tried something like:

new_list = []
for idx1, item1 in enumerate(my_list):
    for idx2, item2 in enumerate(item1):
        new_list[idx1][idx2] = my_dict[item2]

but I get an error when item2 does not exist in the dict. Is there a better way to do this?

Upvotes: 1

Views: 1024

Answers (3)

joseph
joseph

Reputation: 1008

my_list = ['a','b','c','dog', ['pig','cat'], 'd']
my_dict = {'dog':'c','pig':'a','cat':'d'}


def replace(item):
    if item in my_dict:
        return my_dict[item]
    else:
        return item
new_list=[];
for item in my_list:
    if isinstance(item,list):
        temp_list=[]
        for subitem in item:
            temp_list.append(replace(subitem))
        new_list.append(temp_list)
    else:
        new_list.append(replace(item))
print new_list

This piece of code will not work if the list inside my_list is nested in itself.

Upvotes: 0

Kelvin
Kelvin

Reputation: 1367

You look l ike you're trying to substitute into a nested list. Try this function this will recursively swap the values for you:

def replace_vals(_list, my_dict):
    new_list = []
    for item in _list:
        if isinstance(item, list):
              new_list.append(replace_vals(item, my_dict))
        elif item in my_dict:
            new_list.append(my_dict.get(item))
        else:
            new_list.append(item)    
    return new_list

print replace_vals(my_list, my_dict)

Upvotes: 1

niemmi
niemmi

Reputation: 17263

You could write a simple recursive function that uses list comprehension to generate the result. If item on your list is a list then recurse, otherwise use dict.get with default parameter to convert the item:

my_list = ['a','b','c','dog', ['pig','cat'], 'd']
my_dict = {'dog':'c','pig':'a','cat':'d'}

def convert(l, d):
    return [convert(x, d) if isinstance(x, list) else d.get(x, x) for x in l]

print(convert(my_list, my_dict))

Output:

['a', 'b', 'c', 'c', ['a', 'd'], 'd']

Upvotes: 6

Related Questions