Combining a list and multiple dictionaries to nested dictionary - python - python

I want to create a nested dictionary out of a list that should be the keys and dictionaries that are the values of that nested dict.
Input:
l = [key1, key2, key3]
d1 = {string11:value11, string12:value12, string13:value13}
d2 = {string21:value21, string22:value22, string23:value23}
d3 = {string31:value31, string32:value32, string33:value33}
Output:
{key1 : {string11:value11, string12:value12, string13:value13}, key2 : {string21:value21, string22:value22, string23:value23}, key3 : {string31:value31, string32:value32, string33:value33}}
So far, I tried to zip the list and a dict but this creates another dict, not a nested dict.
ld = dict(zip(l,d))
Do I need to create a list of d1,d2,d3 first? How can I combine l and the list of dicts then?

Yes you'll need to create the list of d first
dict(zip(l, [d1, d2, d3]))
When you pass a dictionary in as an iterator, its values will be iterated over (The keys won't be included). Hence why dict(zip(l, d1)) will produce a single dictionary rather than a nested one.

There are many ways. You could for example use dict comprehension:
ld = {k: d for k, d in zip(l, [d1, d2, d3])}

Related

Most efficient way of combining lists inside defaultdict object in Python

I have a defaultdict dictionary, such as:
defaultdict = {
key1: [[objn],[obj0,...objn-1],
key2: [[objm, objm-1],[obj0,...ombjm-2]]
}
This list is created using:
result = collections.defaultdict(list)
for k, vs in groupby(
qs, attrgetter("attr1", "attr2")
):
result[k].append(list(vs))
This is why I have my final dict with a list of lists, I was wondering what would be the most efficient way to combine those lists for each key-value pair?
I can loop over the dictionary and use:
for k in result:
result[k] = list(itertools.chain.from_iterable(result[k]))
Is there a more efficient way to do this in a single loop when creating the result dictionary

Comparing a list to each value of dictionary (which are a list of strings)

I have a list of drugs that I want to compare to a dictionary, where the dictionary keys are drug codes and the dictionary values are lists of drugs. I'd like to only retain the drugs within the dictionary that correspond to the list of drugs.
Example list:
l = ['sodium', 'nitrogen', 'phosphorus']
And dictionary:
d = {'A02A4': ['sodium', 'nitrogen', 'carbon']}
I would want my final dictionary to look like:
{'A02A4': ['nitrogen', 'sodium']}
with the value that is not present in the list removed, and to do this for all key, value pairs in the dictionary
You could use a dictionary comprehension and sets to keep only the values that intersect with the list:
l = ['sodium', 'nitrogen', 'phosphorus']
d = {'A02A4': ['sodium', 'nitrogen', 'carbon']}
{i: list(set(v) & set(l)) for i,v in d.items()}
{'A02A4': ['nitrogen', 'sodium']}
Or equivalently, using intersection:
{i: list(set(v).intersection(l)) for i,v in d.items()}
{'A02A4': ['nitrogen', 'sodium']}

Dictionary comprehension within a list comprehension, per dictionary in other list

I am attempting to create a list of dictionaries, where the dictionaries inside of the list are created from a preexisting list of dictionaries, for which a new dictionary should be created from the aggregate of the key-value pairs of each dictionary in the preexisting list of dictionaries, if the key is a member of another preexisting list (child_container).
Or in other words, I am trying to filter out the keys in the dictionaries (d) in a list of dictionaries (child_container) that are not members of list_multiple_tagnames.
[d for d in child_container if isinstance(d, dict) for k, v in d.iteritems() if k in lst_multiple_tagnames]
The intended effect is for a dictionary to be made PER dictionary d in child_container, with only the Key-Value pairs that are in lst_multiple_tagnames.
A dict comprehension must be used, the compounded for does not capture the per-key-per-dictionary scope.
[{k:v for k,v in d.iteritems() if k in lst_multiple_tagnames} for d in child_container if isinstance(d, dict)]
assume child_container = [{ 1:1,3:324,2:2334}, {1:123},{2:2}]
for d in child_container:
... if isinstance(d,dict):
... for k in d:
... res[k] = res.get(k,[]) + [d[k]]
print res
{1: [1, 123], 2: [2334, 2], 3: [324]}

Python 2.7 append values to dictionary

I have 2 dictionaries with identical keys.
d1 = {'Dog':[7,2],'Cat':[5,2]}
d2 = {'Dog':1,'Cat':4}
Is there a good way of combining them so that I can have one dictionary that looks like this?
d = {'Dog':[7,2,1],'Cat':[5,2,4]}
for key, value in d2.iteritems():
if key in d1:
d1[key].append(value)
If one contains lists and the other contains ints, you can do:
d = {key:[d2[key]] + d1[key] for key in d1}

How to unit a sequence of dicts in Python

I want to unit two dicts, but there are 10 dicts in a list, so how can I unit two by two without duplication?
I wrote something like this:
d_a1 = dict(list(dicts[0].items()) + list(dicts[1].items()))
d_b1 = dict(list(dicts[2].items()) + list(dicts[3].items()))
d_b2 = dict(list(dicts[4].items()) + list(dicts[5].items()))
d_b3 = dict(list(dicts[6].items()) + list(dicts[7].items()))
d_b4 = dict(list(dicts[8].items()) + list(dicts[9].items()))
You could use:
for d1, d2 in zip(dicts[::2], dicts[1::2]):
new_dict = dict(d1, **d2)
This pairs up the dictionaries and creates a new dictionary based on the two input dictionaries.
Further bringing this down to a loop with some iteration magic:
paired = [dict(d1, **d2) for d1, d2 in zip(*[iter(dicts)]*2)]
which produces a list of paired dictionaries.
This creates a list of all paired dictionaries:
it = iter(dicts)
paired_dicts = [dict(x, **next(it)) for x in it]
I would use:
import collections
newDicts = collections.deque((d1.update(d2) for d1,d2 in zip(*[iter(listOfDicts)]*2)), maxlen=0)
This should edit your dictionaries in-place. Thus, all the dictionaries in even numbered indices in your list of dictionaries would contain the union of itself and the dictionary in the very next index

Categories