如何将具有多个值的Dictionary转换为多行中的单个键,将多个值转换为一个键

时间:2018-01-16 07:14:38

标签: python json list dictionary key

以下是我的要求。以下是json文件中的数据:

{"[a]":" text1","[b]":" text2","[a]":" text3","[c]":" text4","[c]":" Text5"}. 

最终输出应该是

{"[a]":[" text1","text3"],"[b]":" text2","[c]":" text4"," Text5"]}.

我尝试了以下代码:

data_in= ["[a]"," text1","[b]"," text2","[a]"," text3","[c]"," text4","[c]"," text5"]
data_pairs = zip(data_in[::2],data_in[1::2])
data_dict = {}
for x in data_pairs:
    data_dict.setdefault(x[0],[]).append(x[1])
print data_dict

但它所采用的输入更多的是List的形式而不是字典。

请告知。

或者有没有办法我可以将原始字典转换为具有多个值的列表,因为列表将只采用唯一值。请让我知道代码,我也是Python的新手,还在学习它。 TIA。

1 个答案:

答案 0 :(得分:0)

键在字典中是唯一的,而值可能不是。

你可以尝试

>>> l = ["[a]"," text1","[b]"," text2","[a]"," text3","[c]"," text4","[c]"," text5"]
>>> dict_data = {}
>>> for i in range(0,len(l),2):
    if dict_data.has_key(l[i]):
        continue
    else:
        dict_data[l[i]] = []


>>> for i in range(1,len(l),2):
    dict_data[l[i-1]].append(l[i])

>>> print dict_data
{'[c]': [' text4', ' text5'], '[a]': [' text1', ' text3'], '[b]': [' text2']}