用重复的键从字符串中创建dict/json [英] make a dict/json from string with duplicate keys Python
问题描述
我有一个可以解析为json或dict对象的字符串.我的字符串变量看起来像这样:
I have a string that could be parsed as a json or dict object. My string variable looks like this :
my_string_variable = "{
"a":1,
"b":{
"b1":1,
"b2":2
},
"b": {
"b1":3,
"b2":2,
"b4":8
}
}"
当我执行json.loads(my_string_variable)
时,我有一个字典,但是仅保留键"b"的第二个值,这是正常的,因为字典不能包含重复的键.
When I do json.loads(my_string_variable)
, I have a dict but only the second value of the key "b" is kept, which is normal because a dict can't contain duplicate keys.
拥有这样的defaultdict的最佳方法是什么:
What would be the best way to have some sort of defaultdict like this :
result = {
'a':1,
'b': [{'b1':1,'b2':2}, { 'b1':3, 'b2':2,'b4':8 } ]
}
我已经在寻找类似的问题,但是它们都将字典或列表作为输入,然后创建defaultdict以处理重复的键.
I have already looked for similar questions but they all deal with dicts or lists as an input and then create defaultdicts to handle the duplicate keys.
在我的情况下,我有一个字符串变量,我想知道是否有一种简单的方法可以实现这个目的:)
In my case I have a string variable and I would want to know if there is a simple way to achieve this :)
谢谢^^
推荐答案
可以完成以下操作.
import json
def join_duplicate_keys(ordered_pairs):
d = {}
for 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)
请注意,上面的代码取决于值类型if type(d[k]) == list
.因此,如果原始字符串本身提供了一个列表,则可能需要一些错误处理才能使代码健壮.
Please note that above code depends on value type, if type(d[k]) == list
. So if original string itself gives a list then there could be some error handling required to make the code robust.
这篇关于用重复的键从字符串中创建dict/json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!