简体   繁体   中英

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.

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:

>>> 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 = []
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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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