-1

There is a dictionary of the following format: [List Containing Dictionaries]

[{'ID': '743987', 'Information': 'Anime is the Best'},
 {'ID': '743987','Information': 'Python is the Best'}]

Required Output:

[
{'ID': '743987','Information': ['Anime is the Best','Python is the Best']}
]

I've seen the other solutions, but none seem to produce the following output:

[ {'ID': '743987','Information': ['Anime is the Best','Python is the Best']} ]

It is necessary for 'ID' and 'Information' to be a part of the output.

How to proceed with this?

1 Answers1

0

You can do it with defaultdict

from collections import defaultdict

res = defaultdict(list)
a = [{'ID': '743987', 'Information': 'Anime is the Best'},
 {'ID': '743987','Information': 'Python is the Best'}]
for i in a:
    for key in i.keys():
        if key == 'ID':
            res[key] = i[key]
        else:
            res[key].append(i[key])
print(dict(res))

Output

{'ID': '743987', 'Information': ['Anime is the Best', 'Python is the Best']}
Leo Arad
  • 4,452
  • 2
  • 6
  • 17
  • is it possible to get the output in the following format: {'ID': '743987','Information': ['Anime is the Best','Python is the Best']}? – Ashish Khatana Jan 25 '21 at 08:36
  • The updated code will do that. – Leo Arad Jan 25 '21 at 08:48
  • It is only working for that string unlike the last version of the code. For example: a = [{'ID': '743987', 'Information': 'Anime is the Best'}, {'ID': '743987','Information': 'Python is the Best'}, {'ID': '743S87','Information': 'OOOOOOO'}] then the generated output is: {'ID': '743S87', 'Information': ['Anime is the Best', 'Python is the Best', 'OOOOOOO']}, completely skips the first ID and combines all the Information Values even though the keys are different. – Ashish Khatana Jan 25 '21 at 09:51