Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用字典中的值字段作为键拆分为多个字典_Python_Python 2.7 - Fatal编程技术网

Python 使用字典中的值字段作为键拆分为多个字典

Python 使用字典中的值字段作为键拆分为多个字典,python,python-2.7,Python,Python 2.7,我有一本Python字典,目前看起来像这样: A = {'Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13','2017-03-13'],'Type':['One','Two','Three','Four','One','Two','Three','Four'],'Value':[1,1,1,1,1,1,1,1]} print A 我想创建一个顶级字典

我有一本Python字典,目前看起来像这样:

A = {'Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13','2017-03-13'],'Type':['One','Two','Three','Four','One','Two','Three','Four'],'Value':[1,1,1,1,1,1,1,1]}
print A
我想创建一个顶级字典,例如类型中的每个唯一值都成为键本身的一部分

这样,在本例中,我的顶级字典将包含四个字典,一个带有键(A,1),下一个带有键(A,2),下一个带有键(A,3),最后一个带有键(A,4)。这些单独DICT中的值将被相应地过滤。因此,第一个底层dict将只具有类型为“1”的值,依此类推

顶级词典将是这四个独特词典的组合。你知道我怎样才能做到这一点吗

from collections import defaultdict

A = {'Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13','2017-03-13'],'Type':['One','Two','Three','Four','One','Two','Three','Four'],'Value':[1,1,1,1,1,1,1,1]}

B=defaultdict(list)
# group by index in the individual lists [ ( D[0], T[0], V[0]), ...]
for (d,t,v) in zip(A["Date"],A["Type"],A["Value"]):
    # each group (D[0],T[0],V[0]) 
    # Create dict B["A" + {"One"}]
    #                    insert in dict B["AOne"][{Date}] = {Value} 
    B["A"+t].append({d:v}) 

print(dict(B))
>>> {'AFour': [{'2017-03-10': 1}, {'2017-03-13': 1}], 'AOne': [{'2017-03-10': 1}, {'2017-03-13': 1}], 'ATwo': [{'2017-03-10': 1}, {'2017-03-13': 1}], 'AThree': [{'2017-03-10': 1}, {'2017-03-13': 1}]}
像这样的


Ideone测试:

您能为您提供的输入添加预期输出吗?这将是对你的问题的一个很好的补充。