【问题标题】:extract all the information from nested dictionary on Python从 Python 上的嵌套字典中提取所有信息
【发布时间】:2020-05-17 05:59:45
【问题描述】:

我正在学习 Python 上的嵌套字典。我想知道如何从嵌套字典中提取特定信息。 我的数据如下:

data = {
    "1": {'area': 'Administration', 'expenditure': '315'},
    "2": {'area': 'Administration', 'expenditure': '120'},
    "3": {'area': None, 'expenditure': '314'},
    "4": {'area': 'Aids and appliances', 'expenditure': None},
    "5": {'area': 'Aids and appliances', 'expenditure': '12'},
    "6": {'area': 'Administration', 'expenditure': '110'},
    "7": {'area': 'Administration', 'expenditure': '300'},
}

如何提取每个领域的所有支出信息? 任何帮助表示赞赏。

【问题讨论】:

  • [el['expenditure'] for el in data.values()] 会给你一份支出清单。
  • 我知道但是如何提取特定区域的所有支出信息?例如,我想提取所有行政支出和所有辅助器具支出
  • aidsappliances 在哪里?
  • 在这样的问题中显示所需的输出真的很有帮助。 extract all the information 是什么意思。那是一本列表字典吗?
  • "4":{'area': '辅助器具', '支出': 无} "5":{'area': '辅助器具', '支出': '12 '}

标签: python python-3.x dictionary


【解决方案1】:

查找expenditure 的键值:

for findvals in data.values():
   for k, v in findvals.items():
      if k == "expenditure":
         print(v)

### this prints all the values for key equal to "expenditure"

【讨论】:

    【解决方案2】:

    你的字典写错了(没有 cmets 和拼写错误!)

    data = 
    {'1': {'area': 'Administration', 'expenditure': '315'},
     '2': {'area': 'Administration', 'expenditure': '120'},
     '3': {'area': None, 'expenditure': '314'},
     '4': {'area': 'Aids and appliances', 'expenditure': None},
     '5': {'area': 'Aids and appliances', 'expenditure': '12'}}
    

    只需这样做:

    [[(v.get("area", None),y) for x,y in v.items() if x=='expenditure'] for k,v in data.items()] 
    

    【讨论】:

      【解决方案3】:

      使用collections.defaultdict。创建一个字典,其中 area 作为键,支出作为列表中的值。

      
      from collections import defaultdict
      
      data = {
      "1": {'area': 'Administration',  'expenditure': '315'},
      "2": {'area': 'Administration', 'expenditure': '120'},
      "3": {'area': None, 'expenditure':'314'},
      "4":{'area': 'Aids and appliances', 'expenditure': None} ,
      "5":{'area': 'Aids and appliances', 'expenditure': '12'},
      "6":{'area': 'Administration', 'expenditure': '110'},
      "7":{'area': 'Administration', 'expenditure': '300'}
      }
      
      storage = defaultdict(list)
      
      # defaultdict allows to define keys on fly
      {storage[d['area']].append(d['expenditure']) for _, d in data.items() if d['area']}
      
      # we have append all expenditure to all areas where the area is not None.
      
      print(storage)
      
      # to go back to normal dictionary with list of expenditures 
      results = dict(storage)
      
      print(results) 
      # outcome: {'Administration': ['315', '120', '110', '300'], 'Aids and appliances': [None, '12']}
      

      如果你不熟悉列表推导,你可以使用普通的for循环:

      # we can re-write this:
      {storage[d['area']].append(d['expenditure']) for _, d in data.items() if d['area']}
      
      # to
      for _, d in data.items():
          if d['area']:
              storage[d['area']].append(d['expenditure'])
      # get all items, and add them to storage if area is not False.
      

      我更喜欢第一个以提高效率,但您可以选择第二个以提高可读性。

      【讨论】:

        【解决方案4】:

        我认为您想要在 specific areas 上指定一个特定的 expenditure。如果您想要所有区域,那么只需从我的代码中删除一个条件,否则您可以参考所有其他答案。 我根据用户输入任何区域名称来执行此操作,他将获得该特定 areaexpenditures

            def findExpense(data):
                a = input("Enter area to find expenditure : ")
                ex_dict = {}
                # create expenditure list as values to ex_dict
                ex_dict[a] = []
                for _,vals in data.items():
                    if vals['area'] == a:
                        ex_dict[a].append(vals['expenditure'])
                return ex_dict
        
            print(findExpense({
                "1": {'area': 'Administration', 'expenditure': '315'},
                "2": {'area': 'Administration', 'expenditure': '120'},
                "3": {'area': None, 'expenditure': '314'},
                "4": {'area': 'Aids and appliances', 'expenditure': None},
                "5": {'area': 'Aids and appliances', 'expenditure': '12'},
                "6": {'area': 'Administration', 'expenditure': '110'},
                "7": {'area': 'Administration', 'expenditure': '300'}
            }))
        

        如果您熟悉list comprehension,那么您可以将for 循环替换为以下代码。

            ex_dict[a] = [vals['expenditure'] for _, vals in data.items() if vals['area'] == a]
            return ex_dict
        

        【讨论】:

        • 你也可以使用 .values() 代替 .items() :)
        • 在我的代码中,如果我使用values() 而不是items(),它将在@Cedric 条件下给出TypeError。所以如果我们使用values(),我们必须修改代码。
        • 对,我想你需要一个演员表。忘记了
        • 是的,是嵌套字典的原因。
        【解决方案5】:

        试试

        [val['expenditure'] for val in data.values() if val['area'] in ['Administration', 'Aids and appliances']]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-09-23
          • 2021-11-05
          • 2014-07-21
          • 1970-01-01
          • 2016-05-15
          • 2021-04-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多