'Python: Create a dictionary where both key and values are also dictionaries out of another dictionary [duplicate]

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



Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

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}}]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 itaisls9
Solution 2 Dhiren Jaypal
Solution 3