简体   繁体   English

计数列表并添加到新字典(Python)

[英]Counting Lists and Adding to a new Dictionary (Python)

I'm working with dictionaries and was wondering how I could output a dictionary where its key is the word that occurs in a given dictionary and its value is the number of times it occurs within that dictionary.我正在使用字典,并且想知道如何 output 一个字典,其中它的键是给定字典中出现的单词,它的值是它在该字典中出现的次数。

So say for example,比如说,

A = {'#1': ['Yellow', 'Blue', 'Red'], '#2': ['White', 'Purple', 'Purple', 'Red']}
B - []
for key in A:
    B.append(A[key])

>>> B
>>> [['Yellow', 'Blue', 'Red'], ['White', 'Purple', 'Purple', 'Red']]

After returning the respective values of the keys, I can now loop through each list of strings and flatten the list of values.返回键的相应值后,我现在可以遍历每个字符串列表并展平值列表。

C = []
for sublist in B:
    for item in sublist:
        C.append(item)

I know that I need to count the number of times the certain strings occur in that list and then populate a dictionary with the key being the colour and the value being how many times it occurs.我知道我需要计算某些字符串在该列表中出现的次数,然后填充字典,其中键是颜色,值是它出现的次数。 This part is mainly where I'm having difficulty.这部分主要是我遇到困难的地方。

You can use a Counter object:您可以使用Counter object:

>>> from collections import Counter
>>> c
['Yellow', 'Blue', 'Red', 'White', 'Purple', 'Purple', 'Red']
>>> Counter(c)
Counter({'Red': 2, 'Purple': 2, 'Yellow': 1, 'Blue': 1, 'White': 1})

Or make your own:或者自己制作:

>>> d = {i: c.count(i) for i in c}
>>> d
{'Yellow': 1, 'Blue': 1, 'Red': 2, 'White': 1, 'Purple': 2}

Also you can make your c creation shorter:您还可以缩短c创建时间:

c = []
for i in A.values():
    c.extend(i)

>>> c
['Yellow', 'Blue', 'Red', 'White', 'Purple', 'Purple', 'Red']

or:或者:

c = [j for i in A.values() for j in i]

>>> c
['Yellow', 'Blue', 'Red', 'White', 'Purple', 'Purple', 'Red']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM