Home > OS >  How to merge values ​of same key in dictionary list?
How to merge values ​of same key in dictionary list?

Time:07-15

I want to merge only msg values in same key

{'id': 'jwYbRVfaQoC0qjbW0OdK_Q', 'status': 'completed', 'results': {'utterances': [{'start_at': 1860, 'duration': 750, 'msg': *'hello'*, 'spk': 1}, {'start_at': 3973, 'duration': 1290, 'msg': *'Good morning'*, 'spk': 0}, {'start_at': 7034, 'duration': 1740, 'msg': *'XXX'*, 'spk': 1}, {'start_at': 8954, 'duration': 1110, 'msg': *'XXX'*, 'spk': 0}]}}

expected result : helloGoodMorningXXXXXX

CodePudding user response:

You can try:

>>> a = {'id': 'jwYbRVfaQoC0qjbW0OdK_Q', 'status': 'completed', 'results': {'utterances': [{'start_at': 1860, 'duration': 750, 'msg': 'hello', 'spk': 1}, {'start_at': 3973, 'duration': 1290, 'msg': 'Good morning', 'spk': 0}, {'start_at': 7034, 'duration': 1740, 'msg': 'XXX', 'spk': 1}, {'start_at': 8954, 'duration': 1110, 'msg': 'XXX', 'spk': 0}]}}
>>> [b["msg"] for b in a["results"]["utterances"]]
['hello', 'Good morning', 'XXX', 'XXX']
>>> "".join([b["msg"] for b in a["results"]["utterances"]])
'helloGood morningXXXXXX'

CodePudding user response:

Here is the solution you can try it:

a={'id': 'jwYbRVfaQoC0qjbW0OdK_Q', 'status': 'completed', 'results': {'utterances': [{'start_at': 1860, 'duration': 750, 'msg': 'hello', 'spk': 1}, {'start_at': 3973, 'duration': 1290, 'msg': 'Good morning', 'spk': 0}, {'start_at': 7034, 'duration': 1740, 'msg': 'XXX', 'spk': 1}, {'start_at': 8954, 'duration': 1110, 'msg': 'XXX', 'spk': 0}]}}
print(a['results']['utterances'])
data = a['results']['utterances']
str_a=''
for a in data:
    str_a = str_a a['msg']

print(str_a)

Output:

helloGood morningXXXXXX

CodePudding user response:

Hiral Talsaniya Solution works but there is little problem using it. Strings are Immutable in python so here in her solution everytime you concat the string it creates completely new string.lets say at some point your utterances array became large say 10000. so at this point it will create 10000 new string to get you the result string so better approach would be use Harsha Biyani Solution. Attaching Screenshot for your reference. check str_a and str_b result at final str_a become the completely new string.

a={'id': 'jwYbRVfaQocoqjbWoodK_Q', 'status': 'completed', 'results': {'utterances': [{'start_at': 1860, "duration':750, 'msg': 'hello', 'spk': 1}, {'start_at': 3973, 'duration': 1290, 'msg': 'Goodmorning', 'spk': 0}, {'start_at': 70 34, "duration': 1740, 'msg': 'XXX', 'spk': 1}, {'start_at': 8954, "duration': 1110, 'msg': 'XXX', 'spk': 0}]}}'
str_a = 'Have a Good Day' 
str_b = str_a 
print(str_b) Have a Good Day
data = a['results']['utterances']
for a in data:
   str_a = str_a   a['msg']
print(str_a)
print(str_b)

Example ScreenShot for Reference

Lesson: Code which looks clean and readable may not be better working solution.

  • Related