How to unpack a dictionary of a list (dictionaries!) And return in the form of grouped tuples?

I have a data structure consisting of mixed dictionaries and lists. I try to unpack it to get tuples of keys and all sub-values โ€‹โ€‹for each key.

I work with a list, but do not get it to work. Where am I mistaken?

I saw many other answers about unpacking the list of lists (for example, 1 , 2 ), but could not find an example when one key is unpacked against several sub-values.

  • desired result โ†’ [('A', 1,2), ('B', 3,4)]
  • actual output โ†’ [('A', 1), ('A', 2), ('B', 3), ('B', 4)]

code:

dict_of_lists = {'A':[{'x':1},{'x':2}], 'B':[{'x':3},{'x':4}] } print [(key,subdict[subkey],) for key in dict_of_lists.keys() for subdict in dict_of_lists[key] for subkey in subdict.keys()] 
+5
source share
2 answers

When the comprehension of the list becomes

  • long
  • incomprehensible / hard to read
  • and most importantly don't work

pull them out and use the guide for cycle (s) each time:

Python 2.x

 def unpack(d): for k, v in d.iteritems(): tmp = [] for subdict in v: for _, val in subdict.iteritems(): tmp.append(val) yield (k, tmp[0], tmp[1]) print list(unpack({'A':[{'x':1},{'x':2}], 'B':[{'x':3},{'x':4}] })) 

Python 3.x

 def unpack(d): for k, v in d.items(): tmp = [] for subdict in v: for _, val in subdict.items(): tmp.append(val) yield (k, *tmp) # stared expression used to unpack iterables were # not created yet in Python 2.x print(list(unpack({'A':[{'x':1},{'x':2}], 'B':[{'x':3},{'x':4}] }))) 

Output:

 [('A', 1, 2), ('B', 3, 4)] 
+5
source

Scroll through the dicts list and get only the values. Then combine with the dict key.

 >>> for k,L in dict_of_lists.iteritems(): ... print tuple( [k]+[v for d in L for v in d.values()]) ('A', 1, 2) ('B', 3, 4) 

If you need one liner:

 >>> map(tuple, ([k]+[v for d in L for v in d.values()] for k,L in dict_of_lists.iteritems())) [('A', 1, 2), ('B', 3, 4)] 
+1
source

Source: https://habr.com/ru/post/1259700/


All Articles