0

I have a list of dictionaries as follows. a,b,c & d values are keys in each individual dictionaries with in the list

I = [{'a':'S1','b':'S2','c':'S3','d':'S4'},{'a':'S5','b':'S6','c':'S7','d':'S8'}]

Now I need to generate a new single dictionary. In that keys are 'a' value & 'b' value. Value for the dictionary is 'd' value. Sample output as follows. Key can be a tuple or a list.

O = {('S1','S2'):'S4',('S5','S6'):'S8'}

Can someone suggest me a method.

martineau
  • 119,623
  • 25
  • 170
  • 301
suresh_chinthy
  • 377
  • 2
  • 12
  • Keys _can't_ be lists because dict keys _[must be immutable](https://stackoverflow.com/questions/24217647/why-must-dictionary-keys-be-immutable)!_ – Pranav Hosangadi Feb 17 '21 at 14:53

1 Answers1

2

Simply use list comprehension as:

I = [{'a':'S1','b':'S2','c':'S3','d':'S4'},{'a':'S5','b':'S6','c':'S7','d':'S8'}]

res = { (elt['a'], elt['b']) : elt['d'] for elt in I }
print(res)

Output:

{('S1', 'S2'): 'S4', ('S5', 'S6'): 'S8'}

Update: using for loop

I = [{'a':'S1','b':'S2','c':'S3','d':'S4'},{'a':'S5','b':'S6','c':'S7','d':'S8'}]

res = dict()
for elt in I:
    res[(elt['a'], elt['b'])] = elt['d']
print(res)
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35