相关疑难解决方法(0)

Python:defaultdict的defaultdict?

有没有办法defaultdict(defaultdict(int))让以下代码工作?

for x in stuff:
    d[x.a][x.b] += x.c_int
Run Code Online (Sandbox Code Playgroud)

d需要根据x.ax.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)

python collections

287
推荐指数
6
解决办法
7万
查看次数

Python:将defaultdict转换为dict

我怎样才能转换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)

python defaultdict

72
推荐指数
3
解决办法
4万
查看次数

Python与嵌套dicts键的dicts汇总列表

我有一个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)

python recursion dictionary

7
推荐指数
1
解决办法
139
查看次数

标签 统计

python ×3

collections ×1

defaultdict ×1

dictionary ×1

recursion ×1