Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy part of dictionary (both its keys and its value)

In my case, I need to transfer part of a dictionary to a persistent storage:

adict={'a':'aaa','b':'bbb','c':'ccc'}
newdict={'a':'aaa','b':'bbb'}

I tried to use dict.fromkeys(['a','b']), this only give me default None Values, unless I specific the value for these keys. What I hope is there is some function automatically default values to the ones the original dict already has. Something like

newdict=adict.fromkeysautomatic(['a','b'])

I know it is easy to write a function to so do so, but I believe there should be some built-in mechanism already, since this should be some frequent behavior. But didn't get it by searching myself.

like image 360
NathaneilCapital Avatar asked Jan 13 '14 04:01

NathaneilCapital


People also ask

Which function is used to get both key and value in dictionary?

get() to get the default value for non-existent keys. You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.

Can two keys have the same value in a dictionary?

Answer. No, each key in a dictionary should be unique. You can't have two keys with the same value.

How do I copy a dictionary key?

By using dict. copy() method we can copies the key-value in a original dictionary to another new dictionary and it will return a shallow copy of the given dictionary and it also helps the user to copy each and every element from the original dictionary.


2 Answers

Using dict comprehension:

>>> d = {'a':'aaa','b':'bbb','c':'ccc'}
>>> newdict = {key:d[key] for key in ['a', 'b']}
>>> newdict
{'a': 'aaa', 'b': 'bbb'}

Side note: Don't use dict as a variable name. It shadows builtin dict function.

like image 185
falsetru Avatar answered Nov 15 '22 16:11

falsetru


Avoiding the dict comprehension which is only available in newer version of Python (2.7+) you can also do:

d = {'a':'aaa','b':'bbb','c':'ccc'}
dd = dict((k, d[k]) for k in ("a", "b"))
like image 26
James Mills Avatar answered Nov 15 '22 15:11

James Mills