I am new to python. I have a query to make.
b = [{a:"1",b:"6"},{a:"1",b:"89"},{a:"2",b:"16"},{a:"2",b:"99"}]
i want to convert this into:
[{a:"1", b: "6. 89"}, {a:"2", "b": "16. 99"}]
Any idea?
I am new to python. I have a query to make.
b = [{a:"1",b:"6"},{a:"1",b:"89"},{a:"2",b:"16"},{a:"2",b:"99"}]
i want to convert this into:
[{a:"1", b: "6. 89"}, {a:"2", "b": "16. 99"}]
Any idea?
# Set up initial data
unmerged = [{"a":"1","b":"6"},{"a":"1","b":"89"},{"a":"2","b":"16"},{"a":"2","b":"99"}]
merged = {}
for entry in unmerged:
entry_a = entry['a']
entry_b = entry['b']
composite_key = entry_a
if composite_key in merged:
merged[composite_key]['b'].append(entry_b)
else:
merged[composite_key] = {
'a': entry_a,
'b': [entry_b]
}
# reconstruct your list with just your unique entries
cleaned = []
for key, value in merged.items():
cleaned.append({
'a': value['a'],
'b': '.'.join(value['b']) # string join b by ". "
})
new_list = [ clean for clean in cleaned ]
print(new_list)
Output:
[{'a': '1', 'b': '6.89'}, {'a': '2', 'b': '16.99'}]
You can try this:
b = [{'a':"1",'b':"6"},{'a':"1",'b':"89"},{'a':"2",'b':"16"},{'a':"2",'b':"99"}]
n = 2
final = [b[i * n:(i + 1) * n] for i in range((len(b) + n - 1) // n )]
finalDict = []
for i in final:
tempDict = {}
for j in i:
for h in j:
if h not in tempDict.keys():
tempDict[h] = j[h]
else:
if tempDict[h]!=j[h]:
tempDict[h]+="."+j[h]
finalDict.append(tempDict)
print(finalDict)