0

I am attempting to replace the first string in the following list using the subsequent dictionary that is mapping to a list of strings.

id_list = ['40000', '58962', '85496']
id_dict = {'10000': ['10001','10002','10003'], '40000': ['40001','40002','40003']}

Using a defined function such as this:

def find_replace_multi_ordered(string, dictionary):
    # sort keys by length, in reverse order
    for item in sorted(dictionary.keys(), key = len, reverse = True):
        string = re.sub(item, dictionary[item], string)
    return string

# Credit: http://pythoninthewyld.com/2018/03/12/dict-based-find-and-replace-deluxe/

In the following for loop:

for i in id_list:

    if id_list[0][-4:] == '0000':
        id_list.replace(find_replace_multi_ordered(i, id_dict))

    else:
        pass

print(id_list)

This works for string to string dictionary mapping but results in a TypeError for sting to list mapping.

Error:

TypeError: unhashable type: 'list'

The desired output would be the following:

id_list = [['40001','40002','40003'], '58962', '85496']

Thank you for any and all recommendations!

1
  • What happens if you type id_dict['4000']? Commented May 28, 2020 at 21:26

2 Answers 2

2

There is much more easy, or each value of the list, if it's in the dict just replace by the pointed value, if it's absent keep the value

Detail of id_dict.get(item, item)

  • first item is the key to look at, to retrieve a value
  • second item is the default value, if the key has not been found
id_list = ['40000', '58962', '85496']
id_dict = {'10000': ['10001','10002','10003'], '40000': ['40001','40002','40003']}

id_list = [id_dict.get(item, item) for item in id_list]
print(id_list) # [['40001', '40002', '40003'], '58962', '85496']
Sign up to request clarification or add additional context in comments.

Comments

0

Does it do what you want?

id_list = ['40000', '58962', '85496']
id_dict = {'10000': ['10001','10002','10003'], '40000': ['40001','40002','40003']}

X = [
    item if item not in id_dict else id_dict[item] for item in id_list
]
print(X) # [['40001', '40002', '40003'], '58962', '85496']

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.