Help me shorten the code and also print the exact same output, as the keys and values may vary every time it runs.
This is the input dictionary:
personal_info_list = [
{"id": 1, "name": "John", "age": 32, "cars": "BMW"},
{"id": 1, "title": "engineer", "cars": "Mercedes", "phone": "samsung"},
{"id": 1, "cars": "Jaguar", "phone": "iphone"},
{"id": 2, "name": "Charlie", "age": 22, "phone": "iphone"},
{"id": 2, "title": "doctor", "cars": "BMW", "phone": "samsung"},
{"id": 3, "name": "Michael", "cars": "Volkswagen", "phone": "nokia"},
{"id": 3, "title": "doctor", "cars": "BMW", "phone": "samsung"},
]
The output dictionary should be like:
{
1: {'name': 'John', 'age': 32, 'cars': ['BMW', 'Mercedes', 'Jaguar'], 'title': 'engineer', 'phone': ['samsung', 'iphone']},
2: {'name': 'Charlie', 'age': 22, 'phone': ['iphone', 'samsung'], 'title': 'doctor', 'cars': 'BMW'},
3: {'name': 'Michael', 'cars': ['Volkswagen', 'BMW'], 'phone': ['nokia', 'samsung'], 'title': 'doctor'}
}
I tried the code to get the all keys of Ids and Merge it with the rest of the dicts:
def formatDictionary(lst_1):
dict1={}
for i in lst_1:
for j in lst_1:
temp=[]
if i['id'] == j['id']:
for k,v in i.items():
S = Merge(i,j)
dict1[i['id']] = S
print(dict1)
formatDictionary(info_list)
Which gave me the output as:
{
1: {'id': 1, 'cars': 'Jaguar', 'phone': 'iphone'},
2: {'id': 2, 'title': 'doctor', 'cars': 'BMW', 'phone': 'samsung'},
3: {'id': 3, 'title': 'doctor', 'cars': 'BMW', 'phone': 'samsung'}
}