1

Say that I have a list of dictionaries that looks like this:

list_1 =[{'A':1, 'B':2, 'C':3, 'D':4 , 'E':5},{'A':6 'B':7, 'C':8, 'D':9 , 'E':10}]

and my desired output is a second list of dictionaries with a single key:value pair, both dictionaries

list_2 = [{{'A':1, 'B':2, 'C':3, 'D':4} : {'E':5}}, {{'A':6 'B':7, 'C':8, 'D':9} : {'E':10}}]

I figured out how to create twom separeted list of dictionaries but I can't seem to find the next step.

list_of_keys = [{key : d[key] for key in set(['A', 'B', 'C', 'D'])} for d in l1]

list_of_values = [{key : d[key] for key in set(['E'])} for d in l1]

thx a lot in advance

3 Answers3

0

You can't use a dictionary as a key for another dictionary since a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable. I recommend you take a look at this thread for a different solution: here

itaisls9
  • 60
  • 4
0

You can't use dictionary for key in dictionary in python.

Dhiren Jaypal
  • 55
  • 1
  • 9
0

Consider using namedtuple instead:

>>> from collections import namedtuple
>>> l1 =[{'A':1, 'B':2, 'C':3, 'D':4, 'E':5}, {'A':6, 'B':7, 'C':8, 'D':9, 'E':10}]
>>> keys = list('ABCD')
>>> Dict = namedtuple('Dict', keys)
>>> [{Dict(*(d.pop(k) for k in keys)): d for d in (d.copy() for d in l1)}]
[{Dict(A=1, B=2, C=3, D=4): {'E': 5}, Dict(A=6, B=7, C=8, D=9): {'E': 10}}]
Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31
  • Not a terrible idea, if the keys are known upfront. But why the `d.pop`? This causes serious side effects. Wouldn't `Dict(**d): d for d in l1` work, too? – xtofl May 18 '22 at 11:51
  • @xtofl Its side effects are exactly what OP expects, aren't they? – Mechanic Pig May 18 '22 at 11:52
  • No: they expect `l2` to contain the result. They didn't say anything about `l1` being altered. – xtofl May 18 '22 at 11:57
  • This is true. That should make a copy of each dictionary, because OP wants the value of the new dictionary not to contain the keys contained in the key dictionary. – Mechanic Pig May 18 '22 at 12:00
  • Your choice of words confuses me. What is this 'the key dictionary' and what was the exact phrasing OP used? Honestly, I like the core of your solution; I would alter it to get rid of the needless side effect. – xtofl May 18 '22 at 12:11
  • The key of the obtained dictionary. OP seems to want the each value not to contain the key contained in the corresponding key of result. @xtofl – Mechanic Pig May 18 '22 at 12:15