[SOLVED] Most efficient way to remove a string pattern of several keys based on a list of patterns and removing duplicate keys


This Content is from Stack Overflow. Question asked by DonCharlie

The objective is to create a clean dictionary key: values pair removing a pattern contained in a list.

pattern_list = ['_PATTERN1','_PATTERN2']
test_dictionary = {'x_PATTERN1': '1', 'y_PATTERN2': 'Okay...'}
#desired result
test_dictionary = {'x': '1', 'y': 'Okay...'}

Have done in the past dict comprehension using this pattern

{k.replace('.', '') : v.replace('.', '') for k, v in x.items()}

However, I wonder how can I use a list instead of a single pattern there.


how about a own function to clean keys?

pattern_list = ['_PATTERN1','_PATTERN2']
def clean_key(key):
    for pattern in pattern_list:
        key = key.replace(pattern, "")
    return key
{clean_key(k) :  v for k, v in x.items()}

This Question was asked in StackOverflow by DonCharlie and Answered by stefan It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?