有没有办法defaultdict(defaultdict(int))让以下代码工作?
for x in stuff:
d[x.a][x.b] += x.c_int
Run Code Online (Sandbox Code Playgroud)
d需要根据x.a和x.b元素进行临时构建.
我可以用:
for x in stuff:
d[x.a,x.b] += x.c_int
Run Code Online (Sandbox Code Playgroud)
但后来我无法使用:
d.keys()
d[x.a].keys()
Run Code Online (Sandbox Code Playgroud) 我怎样才能转换defaultdict
number_to_letter
defaultdict(<class 'list'>, {'2': ['a'], '3': ['b'], '1': ['b', 'a']})
Run Code Online (Sandbox Code Playgroud)
成为一个普通的词典?
{'2': ['a'], '3': ['b'], '1': ['b', 'a']}
Run Code Online (Sandbox Code Playgroud) 我有一个dicts列表,并希望设计一个函数来输出一个新的dict,其中包含列表中所有dicts的每个唯一键的总和.
对于列表:
[
{
'apples': 1,
'oranges': 1,
'grapes': 2
},
{
'apples': 3,
'oranges': 5,
'grapes': 8
},
{
'apples': 13,
'oranges': 21,
'grapes': 34
}
]
Run Code Online (Sandbox Code Playgroud)
到目前为止一切都很好,这可以通过一个计数器完成:
def sumDicts(listToProcess):
c = Counter()
for entry in listToProcess:
c.update(entry)
return (dict(c))
Run Code Online (Sandbox Code Playgroud)
哪个正确返回:
{'apples': 17, 'grapes': 44, 'oranges': 27}
Run Code Online (Sandbox Code Playgroud)
当我的列表中的dicts开始包含嵌套的dicts时出现问题:
[
{
'fruits': {
'apples': 1,
'oranges': 1,
'grapes': 2
},
'vegetables': {
'carrots': 6,
'beans': 3,
'peas': 2
},
'grains': 4,
'meats': 1
},
{
'fruits': {
'apples': 3,
'oranges': …Run Code Online (Sandbox Code Playgroud)