python 如何计算dict list中特定dict键的出现次数以及某些dict值包含list并将计数附加到值中

iswrvxsc  于 2022-11-28  发布在  Python
关注(0)|答案(1)|浏览(117)

我正在计算一个特定的键在dict s的list中出现的次数。我已经使用了循环和求和来计算所有的键,但是我如何才能找到一个特定键的计数呢?我有以下代码,目前还不能使用:

for dico in data:
    for ele in dico['people']:
                  print(ele['name']+str(len(ele['animals'])))

“条目”数据如下所示:

[
  {
    "name": "Uzuzozne",
    "people": [
      {
        "name": "Lillie Abbott",
        "animals": [
          {
            "name": "John Dory"
          }
        ]
      }
    ]
  },
  {
    "name": "Satanwi",
    "people": [
      {
        "name": "Anthony Bruno",
        "animals": [
          {
            "name": "Oryx"
          }
        ]
      }
    ]
  },
  {
    "name": "Dillauti",
    "people": [
      {
        "name": "Winifred Graham",
        "animals": [
          { "name": "Anoa" },
          { "name": "Duck" },
          { "name": "Narwhal" },
          { "name": "Badger" },
          { "name": "Cobra" },
          { "name": "Crow" }
        ]
      },
      {
        "name": "Blanche Viciani",
        "animals":
          [{ "name": "Barbet" },
          { "name": "Rhea" },
          { "name": "Snakes" },
          { "name": "Antelope" },
          { "name": "Echidna" },
          { "name": "Crow" },
          { "name": "Guinea Fowl" },
          { "name": "Deer Mouse" }]
      }
    ]
  }
]

我的目标是通过计算孩子的数量来打印人和动物的计数,并将其附加在名称中,例如Satanwi [2]

[ { name: 'Dillauti [5]',
    people:
     [ { name: 'Winifred Graham [6]',
         animals:
          [ { name: 'Anoa' },
            { name: 'Duck' },
            { name: 'Narwhal' },
            { name: 'Badger' },
            { name: 'Cobra' },
            { name: 'Crow' } ] },
       { name: 'Blanche Viciani [8]',
         animals:
          [ { name: 'Barbet' },
            { name: 'Rhea' },
            { name: 'Snakes' },
            { name: 'Antelope' },
            { name: 'Echidna' },
            { name: 'Crow' },
            { name: 'Guinea Fowl' },
            { name: 'Deer Mouse' } ] },
      ...
...
]
n3schb8v

n3schb8v1#

这将做你想要的;如果您需要解释,请随时询问:

for dico in data:
    children = 0
    for ele in dico['people']:
        animals = len(ele['animals'])
        children += 1 + animals
        ele['name'] += f" [{animals}]"
    dico['name'] += f" [{children}]"

相关问题