简体   繁体   English

如何使用正确的键从Python计数器制作字典?

[英]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. 我对Python和编程都不陌生,因此请原谅一个潜在的愚蠢问题。

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: 我正在使用列表中的collections模块中的Counter方法,并且正在此上使用dict()从结果中制作字典:

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. 解决方案不必包括使用Counter方法,我只想获取一个列表,该列表具有每个状态名称多次,并使用上述字典格式获取每个状态名称被提及的次数。

Iterate over the dictionary items and do printing the keys,values as values of string keys state and other_value . 遍历字典项并打印键,值作为字符串键stateother_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. 这使您可以使用可用形式的数据,而不仅仅是打印输出。

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

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