I have two dictionaries like this:
my_nested_dictionary= {'key5': 'value5',
'key6': {'inner_key6_1': 'inner_value6_1'},
'key7': 'value7'}
empty_dict = {}
If I want to update empty_dict with an inner dict from my_nested_dictionary, I can do that with this code:
for key, value in my_nested_dictionary.iteritems():
if key=='key6':
empty_dictionary.update(value)
However, is there any universal way to do this without using an 'if condition' hardcoded for exactly one key? If I had more nested dictionaries as a value of more keys in my_nested_dictionary, is there a way to update empty_dictionary with all of them at once?
If you don't need to update an existing dictionary and just want a dictionary containing only nested dictionaries, you can do this instead:
only_nested = {k: v for k, v in my_nested_dictionary.items() if isinstance(v, dict)}
For example, given this code:
my_nested_dictionary = {'key5': 'value5',
'key6': {'inner_key6_1': 'inner_value6_1'},
'key7': 'value7',
'key8': {'inner_key8_1': 'inner_value8_1'}}
only_nested = {k: v for k, v in my_nested_dictionary.items() if isinstance(v, dict)}
print(only_nested)
We get this output:
{'key6': {'inner_key6_1': 'inner_value6_1'}, 'key8': {'inner_key8_1': 'inner_value8_1'}}
If you want to check a nested dictionary;
for key, value in my_nested_dictionary.iteritems():
if isinstance(value, dict):
empty_dictionary.update(value)
If you would like to get just get the keys in one statement without using a if, you can do it like (Python 3):
output = list(filter(lambda key: isinstance(my_nested_dictionary[key], dict), my_nested_dictionary.keys()))
output will be like ['key 7'].
From there, you can look it up the vales from the original dictionary as you like. This way you don't have to multiple copies of the same objects.
Related
I have a solution to this question, but I'm curious if there might be a better way.
I have a dict like this:
dict1 = {
'key1':[['value1','value2','value3'],['value4','value5','value6']],
'key2':[['value7','value8','value9'],['value10','value11','value12']],
'key3':[['value13','value14','value15'],['value16','value17','value18']]}
I want to convert this into a nested list, and inserting the keys into the new sublist like this:
nestedlist = [
['value1','value2','key1','value3'],['value4','value5','key1','value6'],
['value7','value8','key1','value9'],['value10','value11','key2','value12'],
['value13','value14','key2','value15'],['value16','value17','key2','value18'],
['value10','value11','key3','value12'],['value13','value14','key3','value15'],
['value16','value17','key3','value18']]
I solve this the following way:
keys = [*dict1]
newlist = []
for item in keys:
for item2 in dict1[item]:
item2.insert(2,item)
newlist.append(item2)
so, how can i improve this piece of code?
Here is one way via a list comprehension:
res = [[w[0], w[1], k, w[2]] for k, v in dict1.items() for w in v]
# [['value1', 'value2', 'key1', 'value3'],
# ['value4', 'value5', 'key1', 'value6'],
# ['value7', 'value8', 'key2', 'value9'],
# ['value10', 'value11', 'key2', 'value12'],
# ['value13', 'value14', 'key3', 'value15'],
# ['value16', 'value17', 'key3', 'value18']]
I would've done it pretty similarly. The only differences shown here:
result = []
for k, l in dict1.items():
for ll in l:
ll.insert(2, k)
result.append(ll)
No need to do list unpacking or doing [] accessing on dict1. items() returns a list of tuples containing each key and value of the dict.
I have two dictionaries as follows:
mydictionary_1 = {1:'apple',2:'banana'}
mydictionary_2 = {1:50,2:30}
The resultant dictionary should be such that it takes the key as the value of first dictionary.
Result_dictionary= {'apple':50, 'banana':30}
You can use a dictionary comprehension using the values of the first dictionary as the keys of the resulting dictionary. This assumes all keys of the first are present in the second dict
{v: dict2[k] for k, v in dict1.items()}
you can also add a check for the presence of the keys in the second dictionary
{v: dictionary_2[k] for k, v in dictionary_1.items() if k in dictionary_2}
Loop through one of the dictionaries and check if the value for a key in mydictionary_1 exists in mydictionary_2.
You can achieve this using python's dictionary comprehension -
Result_dictionary = { v:mydictionary_2[k] for k,v in mydictionary_1.iteritems() if k in mydictionary_2.keys()}
To see how this list comprehension is working you can even use general for loop to loop through each key, value pair in mydictionary_1
for key,value in mydictionary_1.iteritems():
if key in mydictionary_2.keys():
Result_dictionary[value]=mydictionary_2[key]
Dictionary comprehension is an ideal solution for this one, as previously mentioned. Here is a for loop example:
def combine_dictionaries(dict1, dict2):
result_dictionary = {}
for key in dict1.keys():
result_dictionary[dict1[key]] = dict2[key]
return result_dictionary
combine_dictionaries({1:'apple', 2:'banana'}, {1:50, 2:30})
>>>{'apple': 50, 'banana': 30}
This assumes all values of the dict1 are present in the dict2.
def dict_cross_match(dict1, dict2):
new_dict = {}
for item in dict1.keys():
if item in dict2.keys():
new_dict[dict1[item]] = dict2[item]
return new_dict
mydictionary_1 = {1:'apple',2:'banana'}
mydictionary_2 = {1:50,2:30}
print(dict_cross_match(mydictionary_1, mydictionary_2))
given a dictionary with N keys and a tuple of K keys, K<=N is there a pythonic way to get a dictionary with only the K keys?
ex.
orig_dict = {'key1':'value1', 'key2':'value2', ..., 'keyN':'valueN'}
tuple = ('key2', 'keyM')
newdict = myFunc(orig_dict, tuple)
print newdict
Output:
'key2':'value2', 'keyM':'valueM'
You can use a dictionary comprehension:
{k:v for k,v in orig_dict.iteritems() if k in tuple_keys}
Observe:
>>> orig_dict = {'key1':'value1', 'key2':'value2', 'keyN':'valueN'}
>>> tuple_keys = ('key2', 'keyN')
>>> {k:v for k,v in orig_dict.iteritems() if k in tuple_keys}
{'keyN': 'valueN', 'key2': 'value2'}
Just use a comprehension:
tple = ('key2', 'keyM')
{k: orig_dict[k] for k in tple}
Or if you prefer functional:
from operator import itemgetter
dict(zip(tple, itemgetter(*tple)(orig_dict)))
What is more pythonic is debatable, what is definitely not pythonic is using tuple as a variable name.
If some keys may not exist you can get the intersection with viewkeys:
dict(zip(tuple, itemgetter(*orig_dict.viewkeys() & tple)(orig_dict)))
{k : orig_dict[k] for k in orig_dict.viewkeys() & tple}
For python3 just use .keys() which returns a dict_view object as opposed to a list in python2.
If you wanted to give a default value of None for missing keys, you could also use map with dict.get so missing keys would have their value set to None.
dict(zip(tuple, map(orig_dict.get, tuple)
Use a dictionary comprehension
orig_dict = {'key1':'value1', 'key2':'value2', 'keyN':'valueN'}
keys = ('key2', 'keyM')
>>> {k:orig_dict[k] for k in keys if k in orig_dict}
{'key2': 'value2'}
This will be more efficient than iterating over the dictionary's keys and checking whether the key exists in the tuple because it is an O(1) operation to lookup a dict vs O(n) to search in a tuple.
Alternatively you can use a set to get the common keys and combine that with a dict comprehension:
>>> {k:orig_dict[k] for k in set(keys).intersection(orig_dict)}
{'key2': 'value2'}
I am searching for periods "." in a dictionary and trying to delete the key/value pair if I find it
if "." in dict.values():
#delete key, value pair from the dictionary
I am sure this is very simple but I cannot seem to locate an explanation.
Thanks for your help.
Create a new dictionary without those unwanted values using dictionary comprehension. Here is an example of how to do it:
>>> old_dict = {'one': '.', 'two': 2, 'three':3, 'four':'.'}
>>> new_dict = {k:v for k,v in old_dict.iteritems() if not v == '.'}
>>> new_dict
{'three': 3, 'two': 2}
using iteritems instead of items avoids creating an intermediate list and improves performance.
If you don't want to copy your dictionary, (for example if the dictionary is large, or you have a reference to it elsewhere) then you should do it this way:
ks = [k for k in d if d[k]=='.']
for k in ks:
d.pop(k)
Create your list of keys to be removed ahead of time as shown above. You don't want to modify your dictionary while iterating over it.
I'm new to Python and stuck at something basic.
Say there's a list of dictionaries as follows:
[{key1:value1},{key2:value2},...{keyn:valuen}]
is there a pythonic way of extracting the dictionary
{key1:value1},{key2:value2},...{keyn:valuen}
I'm assuming you mean that you want {key1: value1, key2:value2, keyn:valuen}. That is, you want to combine all the separate dictionaries into a single one with each of the keys and values from the individual dictionaries.
Here's how I'd do it, using a dictionary comprehension:
l = [{"key1":"value1"},{"key2":"value2"},{"keyn":"valuen"}]
result = {k:v for d in l for k, v in d.iteritems()}
print result # {'key2': 'value2', 'key1': 'value1', 'keyn': 'valuen'}
Same thing, in perhaps an easier way to read:
result = {}
d_list = [{"key1": "value1"}, {"key2": "value2"}, {"keyn": "valuen"}]
for d in d_list:
for k, v in d.iteritems():
result[k] = v
a=[{1:1},{2:2},{3:3}]
result=dict([(k,v) for x in a for k,v in x.items()])
print result //{1: 1, 2: 2, 3: 3}