1

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?

3 Answers 3

6

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

Comments

1

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)

Comments

0
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.

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.