【问题标题】:get count of actions获取动作计数
【发布时间】:2018-09-04 10:24:41
【问题描述】:

我有嵌套字典,如下所示

{'C_Charges': {'Id': {'action': 'added',
          'new': '##########',
          'old': 'Null'},
         'P_Code': {'action': 'added', 'new': '#####', 'old': 'Null'}},
        'C_Insurance': {'Id': {'action': 'added',
          'new': '#######',
          'old': 'Null'},
         'Ins. Mode': {'action': 'added', 'new': 'Primary', 'old': 'Null'}},
        'C_Status': {'P_Status': {'action': 'Changed',
          'new': 'Waiting',
          'old': 'Blank'},
         'P_Status': {'action': 'Changed', 'new': 'New', 'old': 'Blank'}},
        '[P_Code': 'None'}]},{'C_Status': {'P_Status': {'action': 'Changed',
      'new': 'Blank',
      'old': 'New'}},
    'PTL Status': {'PTL File No': {'action': 'Changed',
      'new': '1',
      'old': '01'},
     'PTL Scan Date': {'action': 'Changed',
      'new': '07/17/2018',
      'old': '07/07/2018'}}}, 

我想计算这样的每一个动作 其中 count = 无重复

{'C_charges:ID:added':counts,
'C_charges:P_Code:added':counts,
'C_Insurance:id:added':counts,
'C_Insurance:Ins. Mode:added':counts,
'C_Status:P_status:changed':counts}

我是 python 新手,所以你的帮助会很有帮助,我也是 stack-overflow 的新手,所以如果编辑错误,请指导我

【问题讨论】:

  • 那么,counts 会在这里吗?
  • count = 无重复
  • 您的字典无效,它有重复的键。
  • 它有重复的键,但在嵌套字典中
  • @benvc 我刚去格式化它并注意到和你一样,你不会偶然完成正确格式化吧?

标签: python python-2.7 dictionary


【解决方案1】:
some_dictionary = {
    'C_Charges': {
        'Id': {'action': 'added','new': '##########','old': 'Null'},
        'P_Code': {'action': 'added', 'new': '#####', 'old': 'Null'}
    },
    'C_Insurance': {
        'Id': {'action': 'added','new': '#######','old': 'Null'},
        'Ins. Mode': {'action': 'added', 'new': 'Primary', 'old': 'Null'}
    },
    'C_Status': {
        'P_Status': {'action': 'Changed','new': 'Waiting','old': 'Blank'},
        'P_Status': {'action': 'Changed', 'new': 'New', 'old': 'Blank'},
        'P_Code': {'None':'None'},
        'PTL Status': {
            'PTL File No': {'action': 'Changed','new': '1','old': '01'}
        },
        'PTL Scan Date': {
            'action': 'Changed','new': '07/17/2018', 'old': '07/07/2018'
        }
    }
}

这适用于正在处理此代码的任何人,我试图格式化字典,由于括号不正确,我不得不删除一些重复项并做出一些假设。我认为我们仍然可以使用它来提出一个解决方案,一旦 OP 有正确的字典设置就可以工作。

如果 OP 可以查看并评论缺少或不需要的内容,我会更新。

在这里假设,OP 想要找到所有 action,其中 value 是唯一的,所以我们将检索 addedChanged,只是试图将它们拼凑在一起,任何人都可以随意加入。

解决方案

for k, v in some_dictionary.items():
    for a, b in v.items():
        if k == 'C_Status' and a == 'P_Code':
            continue
        elif a != 'PTL Status':
            status = [v for k, v in b.items() if k == 'action']
            status = ''.join(status)
            name = f"{k}: {a}: {status}" 
            actions = []
            actions.append(b.get('action'))
            actions = set(actions)
            count = 0
            for i in actions:
                count += 1
            print(f"{name}: counts: {count}")
        elif a == 'PTL Status':
            for e, f in b.items():
                status = [v for k, v in f.items() if k =='action'] 
                status = ''.join(status)
                name = f"{k}: {a}: {status}"
                actions= []
                actions.append(f.get('action'))
                actions = set(actions)
                count = 0 
                for i in actions:
                    count +=1
                print(f"{name}: counts: {count}")

输出

(xenial)vash@localhost:~/python$ python3.7 dict.py
C_Charges: Id: added: counts: 1
C_Charges: P_Code: added: counts: 1
C_Insurance: Id: added: counts: 1
C_Insurance: Ins. Mode: added: counts: 1
C_Status: P_Status: Changed: counts: 1
C_Status: PTL Status: Changed: counts: 1
C_Status: PTL Scan Date: Changed: counts: 1

我确信有更好的方法来做到这一点,但我会分解我的方法并向您展示我是如何接近它的。为此,我将使用 dict.get() 函数,您可以在此处阅读 https://www.codzify.com/Python/python_dictionary.php

第一步

首先让我们看看我们如何到达每个action 为此,我们需要弄清楚哪些嵌套的dict 包含action 以便我们正确访问

我们跑吧:

for k, v in some_dictionary.items():
    print(f"""
        {k}
        ---
        {v}

     """)

这会返回:

(xenial)vash@localhost:~/python$ python3.7 dict.py

    C_Charges
    ---
    {'Id': {'action': 'added', 'new': '##########', 'old': 'Null'}, 'P_Code': {'action': 'added', 'new': '#####', 'old': 'Null'}}



    C_Insurance
    ---
    {'Id': {'action': 'added', 'new': '#######', 'old': 'Null'}, 'Ins. Mode': {'action': 'added', 'new': 'Primary', 'old': 'Null'}}



    C_Status
    ---
    {'P_Status': {'action': 'Changed', 'new': 'New', 'old': 'Blank'}, 'P_Code': {'None': 'None'}, 'PTL Status': {'PTL File No': {'action': 'Changed', 'new': '1', 'old': '01'}}, 'PTL Scan Date': {'action': 'Changed', 'new': '07/17/2018', 'old': '07/07/2018'}}

从这里我可以看到action 表示位于另一个嵌套字典中的key,该字典嵌套在v

所以现在我们可以将v 视为字典。让我们看看使用另一个 for 循环打印 key's 和 value's for v.items()

for k, v in some_dictionary.items():
    for a, b in v.items():
        print(f"""
            {a}
            ----
            {b}
            ---
        """)

打印出来:

(xenial)vash@localhost:~/python$ python3.7 dict.py

        Id
        ----
        {'action': 'added', 'new': '##########', 'old': 'Null'} 


        P_Code
        ----
        {'action': 'added', 'new': '#####', 'old': 'Null'}


        Id
        ----
        {'action': 'added', 'new': '#######', 'old': 'Null'}


        Ins. Mode
        ----
        {'action': 'added', 'new': 'Primary', 'old': 'Null'}


        P_Status
        ----
        {'action': 'Changed', 'new': 'New', 'old': 'Blank'}   


        P_Code
        ----
        {'None': 'None'}    


        PTL Status
        ----
        {'PTL File No': {'action': 'Changed', 'new': '1', 'old': '01'}} 



        PTL Scan Date
        ----
        {'action': 'Changed', 'new': '07/17/2018', 'old': '07/07/2018'}

好的,现在我可以看到action 代表b 中的key,这是一个字典,因此我可以使用b.get('action') 并取回正确的值。

除了PTL Status,这里我看到key 更深了。如果我们看一下,它实际上是在一个字典中,它是一个字典的 valuePTL Statusvalue,所以我需要将 PTL Statusvalue 作为字典来查看。

让我们试试这个:

for k, v in some_dictionary.items():
    for a, b in v.items():
        # later this will be b.get('action'), but hang on
        if a == 'PTL Status':
            for e, f in b.items():
                print(f)

现在我们得到:

(xenial)vash@localhost:~/python$ python3.7 dict.py
{'action': 'Changed', 'new': '1', 'old': '01'}

这告诉我actionkey 在字典中f 我可以找到它。 所以我有一条通往每个key 的途径,可以将dict.get('key') 应用到,并获得我想要的所有values

在实践中,这些路径如下所示:

for k, v in some_dictionary.items():
    for a, b in v.items():
        if k == 'C_Status' and a == 'P_Code':
            continue
        elif a != 'PTL Status':
            b.get('action')
        elif a == 'PTL Status':
            for e, f in b.items():
                f.get('action')

这里代码的唯一补充是if k == 'C_Status' and a == 'P_Code': continue,这是为了忽略P_Code,只针对C_Status,因为它将返回None

第 2 步

我们现在的目标是计算每个类别的所有这些独特的action。 在我看来,这意味着我们必须为每个循环创建一个actionsappend 的所有值的列表,并将其设为set,这样我们就没有重复项。从那里我们必须计算set 中的每个item。让我们看看如何做到这一点:

for k, v in some_dictionary.items():
    for a, b in v.items():
        if k == 'C_Status' and a == 'P_Code':
            continue
        elif a != 'PTL Status':
            actions = []
            actions.append(b.get('action'))
            actions = set(actions)
            count = 0
            for i in actions:
                count += 1
        elif a == 'PTL Status':
            for e, f in b.items():
                actions = []
                actions.append(f.get('action'))
                actions = set(actions)
                count = 0
                for i in actions:
                    count += 1

请注意,b.getf.get 的使用也在每个循环开始时重置 actions = []count = 0,因为我们不需要它们来运行我们想要的所有东西的 count count 分别针对每个类别。

第 3 步

最后让我们根据要求以适当的格式打印所有内容:

{'C_charges:ID:added':counts,
'C_charges:P_Code:added':counts,
'C_Insurance:id:added':counts,
'C_Insurance:Ins. Mode:added':counts,
'C_Status:P_status:changed':counts}

使用此模板,我尝试了解print 这种格式所需的一切。

对于C_*Categories,我可以只使用它在for 循环中表示的变量,在每种情况下,这将是some_dictionary.items() 中的k

对于子类别ID, P_Code, ...,我可以使用来自for a, b in v.items() 的变量a

现在得到addedchanged这个词,我将其称为status(回想起来应该更像state以避免与P_Status混淆),我们将使用字典理解,在提供的链接中进行了解释,看起来像这样:

status = [v for k, v in b.items() if k =='action']

对于PTL Status

status = [v for k, v in f.items() if k == 'action']

当我们打印status 时,它看起来像['added'],但我只想要added,所以我多写了一行:

status = ''.join(status)

我将使用我必须的变量来构造一个可以打印并存储为name 的语句,如下所示:

`name = f"{k}: {a}: {status}"

最后我们可以将它与countprint 组合成这样的语句:

`print(f"{name}: counts: {count}")`

把它们放在一起:

for k, v in some_dictionary.items():
    for a, b in v.items():
        if k == 'C_Status' and a == 'P_Code':
            continue
        elif a != 'PTL Status':
            status = [v for k, v in b.items() if k == 'action']
            status = ''.join(status)
            name = f"{k}: {a}: {status}" 
            actions = []
            actions.append(b.get('action'))
            actions = set(actions)
            count = 0
            for i in actions:
                count += 1
            print(f"{name}: counts: {count}")
        elif a == 'PTL Status':
            for e, f in b.items():
                status = [v for k, v in f.items() if k =='action'] 
                status = ''.join(status)
                name = f"{k}: {a}: {status}"
                actions= []
                actions.append(f.get('action'))
                actions = set(actions)
                count = 0 
                for i in actions:
                    count +=1
                print(f"{name}: counts: {count}")

嗯,我希望这对我有帮助,我必须自学一些东西才能完成它,我相信有人可以做得更好,但这就是我所得到的,希望它有所帮助!

另外我会再看一下提供的字典,有些东西看起来很奇怪,就像 PTL File No 有一个动作但嵌套在 PTL Status 中,它没有动作但看起来像 PTL File No 应该有与PTL Status处于同一深度。评论如果你需要什么我会在附近。

【讨论】:

  • 感谢@vash_the_stampede 格式化我的字典请现在可以给我解决问题
  • @MuhammadWaleed 我在格式化字典时实际上不知道如何完成这项任务,我只是希望帮助有人为您解决这个问题,但我昨晚才知道去睡觉,为你整理一下这个解决方案
  • @MuhammadWaleed 还要确保更新您的字典,以便C_Status: {'P_Code'} : {'None':'None'}
  • @MartinR,这样更好吗?正在尝试,寻找意见以改进我的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多