dict中唯一嵌套值的计数

2024-09-30 01:26:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类似这样的模式,我想得到journal,其中提到了唯一drugs的最大数量

    my_list = [{'atccode': 'A04AD',
  'drug': 'DIPHENHYDRAMINE',
  'mentioned_in': [{'date': '01/01/2019',
                    'journal': 'Journal of emergency nursing'},
                   {'date': '01/01/2019',
                    'journal': 'Journal of emergency nursing'
                    },
                   {'date': '1 January 2020',
                    'journal': 'Journal of emergency nursing'
                    },
                   {'date': '1 January 2020',
                    'journal': 'Journal of emergency nursing'},
                   {'date': '1 January 2020',
                    'journal': 'Journal of emergency nursing'
                    }]},
 {'atccode': 'S03AA',
  'drug': 'TETRACYCLINE',
  'mentioned_in': [{'date': '02/01/2020',
                    'journal': 'American journal of veterinary research'
                    },
                   {'date': '2020-01-01',
                    'journal': 'Psychopharmacology'}]},
 {'atccode': 'V03AB',
  'drug': 'ETHANOL',
  'mentioned_in': [{'date': '2020-01-01',
                    'journal': 'Psychopharmacology'
                    }]},
 {'atccode': 'A01AD',
  'drug': 'EPINEPHRINE',
  'mentioned_in': [{'date': '01/02/2020',
                    'journal': 'The journal of allergy and clinical '
                               'immunology. In practice'},
                   {'date': '01/03/2020',
                    'journal': 'The journal of allergy and clinical '
                               'immunology. In practice'
                    },
                   {'date': '27 April 2020',
                    'journal': 'Journal of emergency nursing'
                    }]}]

因此,结果将如下所示:

    {
         "journal":"Psychopharmacology",
         "unique_drug_mentions" : 2
    },
    {
         "journal" : "Psychopharmacology",
         "unique_drug_mentions":2

    }

到目前为止我一直在尝试的是

from collections import Counter

mentions_counts = Counter(d['journal'] for d in my_list)
most_common = {'unique_drug_mentions': mentions_counts.most_common(1)[0][0], "journal" :d["journal"]}

但它不起作用


Tags: ofindatemyjournaluniquementionsnursing
1条回答
网友
1楼 · 发布于 2024-09-30 01:26:33

我会循环浏览我的列表:

# store counts of unique drugs here
counts = {}

# loop through your dicts in the list
for d in my_list:

    # look in each journal mention
    for d2 in d['mentioned_in']:

        # if we haven't seen this journal before
        if d2['journal'] not in counts:
            counts[d2['journal']] = set()

        counts[d2['journal']].add(d['drug'])

# this would have all your verbose info as you want it
unique_drug_counts = [
    {
        "journal": journal,
        "unique_drug_mentions": len(drugs)
    }
    for journal, drugs in counts.items()
]

# max value (the answer to your question
max(counts.items(), key=lambda x: len(x[1]))

相关问题 更多 >

    热门问题