Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-line expression to map dictionary to another

Tags:

python

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?

like image 745
Alex G.P. Avatar asked Jan 15 '11 09:01

Alex G.P.


People also ask

How do you map a dictionary value?

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.

How do I print a dictionary on one line?

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.

Can map function be used on dictionary?

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.

How do you make a dictionary one line?

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 .


1 Answers

Sure:

d = dict((m.get(k, k), v) for (k, v) in d.items())
like image 163
Karl Knechtel Avatar answered Nov 14 '22 13:11

Karl Knechtel