简体   繁体   English

从列表创建嵌套字典

[英]Creating nested dictionaries from a list

Sorry for a 3rd similar question but I'm still trying to work through what my output would be.很抱歉出现了第三个类似的问题,但我仍在努力解决我的输出是什么。

Ideally I would have programmatic way using a function to take a list of values and store them in a nested dictionary.理想情况下,我会以编程方式使用函数来获取值列表并将它们存储在嵌套字典中。

values = [1,2.0,3.0,1,1,3,4.0,2,3.0, 2.0]

The result of the function would provide a dictionary that looks like this:该函数的结果将提供一个如下所示的字典:

types: {

   'int' : {
       
       '1': [1,1,1,],
       '2': [2],
       '3': [3]
       }
    'float' : {
       '2.0' : 2,
       '3.0' : 2,
       '4.0' : 1
      }
}

Where the int dictionary just stores the occurrences of each value and the float dictionary stores the counts of the instances. int 字典只存储每个值的出现次数,而 float 字典存储实例的计数。

This is what I have but I'm running into problems with the logic of creating the sub dictionaries.这就是我所拥有的,但我遇到了创建子词典的逻辑问题。

values = [1,2.0,3.0,1,1,3,4.0,2,3.0, 2.0]

types = {}
for obj in values:
      k = type(obj).__name__
      types[k] = types.get(k, {})
      if isinstance(obj, int):
          types['int'] = obj
      elif isinstance(obj, float):
         types['float'][obj] = types['float'].get(obj,0)
            
print(types)

I started with a for loop to try to figure out the logic before try the我从一个 for 循环开始尝试在尝试之前找出逻辑

def summarize_numbers(list):
return type

function syntax函数语法

I guess this should help you reach the solution you need我想这应该可以帮助您找到所需的解决方案

values = [1,2.0,3.0,1,1,3,4.0,2,3.0, 2.0]
types= {'int':{}, 'float':{}}

for obj in values:
    if isinstance(obj, int):
        obj = str(obj)
        types['int'][obj] = types['int'].get(obj, [])
        types['int'][obj].append(int(obj))
    elif isinstance(obj, float):
        obj = str(obj)
        types['float'][obj] = types['float'].get(obj, 0) + 1

print(types)

Output:输出:

{'int': {'1': [1, 1, 1], '3': [3], '2': [2]}, 'float': {'2.0': 2, '3.0': 2, '4.0': 1}}

Using your code as much as possible尽可能多地使用你的代码

values = [1,2.0,3.0,1,1,3,4.0,2,3.0, 2.0]

types = {}
for obj in values:
      k = type(obj).__name__
      types[k] = types.get(k, {})
      if isinstance(obj, int):
            types[k].setdefault(obj, []).append(obj) # append to default list
      elif isinstance(obj, float):
        types[k].setdefault(obj, 0)  # default int 0
        types[k][obj] += 1           # increment

print(types) # {'int': {1: [1, 1, 1], 3: [3], 2: [2]}, 
                'float': {2.0: 2, 3.0: 2, 4.0: 1}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM