我有一个JSON对象,它是这样的:
{ "produktNr:"1234",
"artNr_01":"12",
"artNr_02":"23",
"artNr_03":"",
"artNr_04":"14",
"name_01":"abc",
"name_02":"der",
"test":"junk"
}
我想把它转换成这样的字典:
{ "produktNr:"1234", "artNr":["12","23","","14"], "name":["abc","der"], "test":"junk"}
这种转换是基于给定的序列,例如seq = ["artNr","name"]
。因此,在字典的键中搜索序列的内容,并将值收集到一个列表中。你知道吗
我目前的尝试:
tempDict = {}
for key,value in fmData.iteritems():
for seqval in seq:
if seqval in key:
if seqval in tempDict:
tempDict[seqval].append(value)
else:
x = []
x.append(value)
tempDict[seqval]=x
else:
tempDict[key] = value
面临一些问题。你知道吗
值列表没有顺序,即"artNr":["","14","12","23"]
而不是[_01,_02,_03,_04]
无法从字典中弹出项,因为在循环中无法删除字典项,从而导致:
{“produktNr:”1234“,”artNr“:[”12“,”23“,”14“],”artNr\u 01“:”12“,”artNr\u 02“:”23“,”artNr\u 03“,”artNr\u 04“:”14“,”name“:[”abc“,”der“,”name\u 01“:”abc“,”name\u 02“:”der“,”test“:”junk“}
我很想知道如何处理这个问题,特别是如果有一个Python的方法来解决这个问题。你知道吗
您可以使用
OrderedDict
包中的collections
:从而得到所需的输出
您可以重新创建一个新的字典,该字典将使用列表中键中的
'_'
对键的值进行分组,而其他键和值则保持不变。这应该做到:dict是
unordered
集合,因此值附加到列表的顺序将是不确定的。你知道吗对代码稍作修改:
结果:
相关问题 更多 >
编程相关推荐