如果数据显示为字典:
dct = {'s1': "MP", 's2': "GP", 's3': "MP"}
但我想根据他们的指数来映射每个值的相应位置,以便我得到:
{0: {'s1': "M", 's2': "G", 's3': "M"}, 1: {'s1': "P", 's2': "P", 's3': "P"}}
我应该如何在python中使用它?
我尝试以标准方式分解原始字典,并使用enumerate()
方法:
# create a variable to store a nested dict
IndexDict = {}
# decompose the original dict
for key, value in dct.iteritems():
#print key
#print value
for i, v in enumerate(value):
#print i
#print v
# my attempt here to create a nested dict of the form {0:{s1:"M",S2:"G", s3:"M"},1:{s1:"P",s2:"P",s3:"P"}} fails!
IndexDict[i][key] = v
# printIndexDict returns an error
答案 0 :(得分:2)
您需要添加嵌套字典来保存给定索引的键 - 字符对(如果它尚不存在)。您可以使用defaultdict()
或使用dict.setdefault()
。
IndexDict = {}
for key, value in dct.iteritems():
for i, v in enumerate(value):
IndexDict.setdefault(i, {})[key] = v
如果第一个参数(一个键)不存在,该方法将第二个参数添加为值,然后返回键的值(即新对象或已存在的对象)。
或使用collections.defaultdict()
object:
from collections import defaultdict
IndexDict = defaultdict(dict)
for key, value in dct.iteritems():
for i, v in enumerate(value):
IndexDict[i][key] = v
defaultdict
是dict
的子类,如果缺少键,则调用给定的工厂参数;这里是dict()
所以如果i
不存在,则为您添加新词典。
演示:
>>> dct = {'s1': "MP", 's2': "GP", 's3': "MP"}
>>> IndexDict = {}
>>> for key, value in dct.iteritems():
... for i, v in enumerate(value):
... IndexDict.setdefault(i, {})[key] = v
...
>>> IndexDict
{0: {'s3': 'M', 's2': 'G', 's1': 'M'}, 1: {'s3': 'P', 's2': 'P', 's1': 'P'}}
>>> from collections import defaultdict
>>> IndexDict = defaultdict(dict)
>>> for key, value in dct.iteritems():
... for i, v in enumerate(value):
... IndexDict[i][key] = v
...
>>> IndexDict
defaultdict(<type 'dict'>, {0: {'s3': 'M', 's2': 'G', 's1': 'M'}, 1: {'s3': 'P', 's2': 'P', 's1': 'P'}})