首页 > 解决方案 > 获取动作计数

问题描述

我有嵌套字典,如下所示

{'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'}}}, 

我想要这样的每一个动作的计数,其中计数 = 不重复

{'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 的新手,所以如果编辑错误,请指导我

标签: pythonpython-2.7dictionary

解决方案


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,所以我们会检索added并且Changed,只是试图将它们拼凑在一起,任何人都可以随意加入。

解决方案

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表示 akey其中b是字典,因此我可以使用b.get('action')并取回正确的值。

除了PTL Status,在这里我看到的key更深。如果我们看,它实际上在一个字典中,它是一个value字典,value所以PTL Status我需要将PTL Status'svalue看作字典。

让我们试试这个:

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_Codefor ,C_Status因为它将返回None

第2步

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

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.get我在每个循环开始时f.get重置了actions = []and 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它都将k在中。some_dictionary.items()

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

现在要获取单词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. 评论如果你需要什么我会在附近。


推荐阅读