make a dict/json from string with duplicate keys Python -
i have string parsed json or dict object. string variable looks :
my_string_variable = "{ "a":1, "b":{ "b1":1, "b2":2 }, "b": { "b1":3, "b2":2, "b4":8 } }"
when json.loads(my_string_variable)
, have dict second value of key "b" kept, normal because dict can't contain duplicate keys.
what best way have sort of defaultdict :
result = { 'a':1, 'b': [{'b1':1,'b2':2}, { 'b1':3, 'b2':2,'b4':8 } ] }
i have looked similar questions deal dicts or lists input , create defaultdicts handle duplicate keys.
in case have string variable , want know if there simple way achieve :)
thank ^^
something following can done.
import json def join_duplicate_keys(ordered_pairs): d = {} k, v in ordered_pairs: if k in d: if type(d[k]) == list: d[k].append(v) else: newlist = [] newlist.append(d[k]) newlist.append(v) d[k] = newlist else: d[k] = v return d raw_post_data = '{"a":1, "b":{"b1":1,"b2":2}, "b": { "b1":3, "b2":2,"b4":8} }' newdict = json.loads(raw_post_data, object_pairs_hook=join_duplicate_keys) print (newdict)
please note above code depends on value type, if type(d[k]) == list
. if original string gives list there error handling required make code robust.
Comments
Post a Comment