Home > database >  Create New Dict from Existing DIct Using List of Values
Create New Dict from Existing DIct Using List of Values

Time:11-25

I have a list of values and want to create a new dictionary from an existing dictionary using the key/value pairs that correspond to the values in the list. I can't find a Stackoverflow answer that covers this.

example_list = [1, 2, 3, 4, 5]

original_dict = {"a": 1, "b": 2, "c": 9, "d": 2, "e": 6, "f": 1}

desired_dict = {"a": 1, "b": 2, "d": 2, "f": 1}

Note that there are some values that are assigned to multiple keys in original_dict (as in the example).

Any help would be appreciated.

Thanks

CodePudding user response:

You can use dict comprehension or you can use filter.

example_list = [1, 2, 3, 4, 5]

original_dict = {"a": 1, "b": 2, "c": 9, "d": 2, "e": 6, "f": 1}

desired_dict = {key: value for key, value in original_dict.items() if value in example_list}

# Option_2
desired_dict = dict(filter(lambda x: x[1] in example_list, original_dict.items()))
# -------------------------------^^^ x[0] is key, x[1] is value of 'dict'

print(desired_dict)

Output:

{'a': 1, 'b': 2, 'd': 2, 'f': 1}

CodePudding user response:

You could pass original_dict.items() to filter and then the results of filter can be recast to dict.

el = [1, 2, 3, 4, 5]

od = {"a": 1, "b": 2, "c": 9, "d": 2, "e": 6, "f": 1}

# `i` will be (key,value)
dd = dict(filter(lambda i: i[1] in el, od.items()))

print(dd) #{"a": 1, "b": 2, "d": 2, "f": 1}
  • Related