I have dictionary like
d = {'user_id':1, 'user':'user1', 'group_id':3, 'group_name':'ordinary users'}
and "mapping" dictionary like:
m = {'user_id':'uid', 'group_id':'gid', 'group_name':'group'}
All i want to do is "replace" keys in first dictionary with values from the second one. The expected output is:
d = {'uid':1, 'user':'user1', 'gid':3, 'group':'ordinary users'}
I know that keys are immutable and i know how to do it with 'if/else' statement.
But maybe there is way to do it in one line expression?
Write a Python program to map the values of a given list to a dictionary using a function, where the key-value pairs consist of the original value as the key and the result of the function as the value. Use map() to apply fn to each value of the list. Use zip() to pair original values to the values produced by fn.
Print a dictionary line by line using for loop & dict. items() dict. items() returns an iterable view object of the dictionary that we can use to iterate over the contents of the dictionary, i.e. key-value pairs in the dictionary and print them line by line i.e.
We can use the Python built-in function map() to apply a function to each item in an iterable (like a list or dictionary) and return a new iterator for retrieving the results.
The one-liner dict(enumerate(a)) first creates an iterable of (index, element) tuples from the list a using the enumerate function. The dict() constructor than transforms this iterable of tuples to (key, value) mappings. The index tuple value becomes the new key . The element tuple value becomes the new value .
Sure:
d = dict((m.get(k, k), v) for (k, v) in d.items())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With