简体   繁体   中英

How do I make a dictionary from a Python counter with the right keys?

I am new to both Python and programming so please forgive a potentially stupid question.

I am using the Counter method from the collections module on a list and I am using dict() on this to make a dictionary from the results:

state_count = ['Alabama','Alabama','Alabama','Alaska','Alaska']
print dict(Counter(state_count))

The data comes out looking like this:

{'Alabama': '3', 'Alaska': '2'} etc.

What I want is to create a dictionary where the state name is a key and it would look like this:

{'state':'Alabama','other_value':'3'}
{'state':'Alaska','other_value':'2'}

The solution doesn't have to include using the Counter method, I just want to take a list that has each state name multiple times and get a count of how many times each state name is mentioned using the above dictionary format.

Iterate over the dictionary items and do printing the keys,values as values of string keys state and other_value .

from collections import Counter
state_count = ['Alabama','Alabama','Alabama','Alaska','Alaska']
m = Counter(state_count)
for i, j in m.items():
    print {'state':i, 'other_value':j}

Output:

{'state': 'Alabama', 'other_value': 3}
{'state': 'Alaska', 'other_value': 2}

If you want to use the data in a list of dicts format, you can easily create such a list:

from collections import Counter
state_count = ['Alabama','Alabama','Alabama','Alaska','Alaska']
dict_list = [{"state":k,"other_value":v} for k,v in Counter(state_count).items()]

print dict_list[0] #{'state': 'Alabama','other_value': 3}
print dict_list[0]["state"] #'Alabama'

This leaves you with the data in a usable form and not just printed output.

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