0

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
TrickOrTreat
  • 821
  • 1
  • 9
  • 23
  • 1
    or this https://stackoverflow.com/questions/60219526/merge-list-of-dictionaries-where-id-is-duplicate-python3 – mrEvgenX Feb 14 '20 at 07:27

2 Answers2

5
# 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'}]
smack cherry
  • 471
  • 3
  • 7
-2

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)
Vaibhav Jadhav
  • 2,020
  • 1
  • 7
  • 20