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.
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.
Answer. No, each key in a dictionary should be unique. You can't have two keys with the same value.
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.
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.
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"))
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