我有一个列表:
List_ = ["Peter", "Peter", "Susan"]
我想做一个这样的字典:
Dict_ = {"Name": "Peter", "Count": 2, "Name": "Susan", "Count": 1}
Dict_ = {}
Dict_new = {}
for text in List_:
if text not in Dict_:
Dict_[text] = 1
else:
Dict_[text] += 1
for key, values in Dict_.items():
Dict_new["Name"] = key
Dict_new["Count"] = values
print(Dict_new)
它只打印最后一个:
{"Name": "Susan", "Count": 1}
下面是您可以根据自己的喜好使用的实现:
from collections import Counter
# Your data
my_list = ["Peter", "Peter", "Susan"]
# Count the occurrences
counted = Counter(my_list)
# Your format
counted_list = []
for key, value in counted.items():
counted_list.append({"Name": key, "Count": value})
print(counted_list)
输出为:
[{'Name': 'Peter', 'Count': 2}, {'Name': 'Susan', 'Count': 1}]
如注释所述,字典中每个键只能有一次。
您可能需要一个字典列表,使用collections.Counter
的帮助和列表理解构建。
>>> from collections import Counter
>>> List_ = ["Peter", "Peter", "Susan"]
>>> [{'name': k, 'count': v} for k, v in Counter(List_).items()]
[{'name': 'Peter', 'count': 2}, {'name': 'Susan', 'count': 1}]
除了使用collections.Counter
,还可以使用defaultdict
。
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for n in List_:
... d[n] += 1
...
>>> d
defaultdict(<class 'int'>, {'Peter': 2, 'Susan': 1})
>>> [{'name': k, 'count': v} for k, v in d.items()]
[{'name': 'Peter', 'count': 2}, {'name': 'Susan', 'count': 1}]
您可以使用下面的代码来实现您想要做的事情。
List_ = ["Peter", "Peter", "Susan"]
dict_ = {}
for name in List_:
if name in dict_:
dict_[name] += 1
else:
dict_[name] = 1
print(dict_)
生成以下输出,其中key为名称,value为计数。
{'Peter': 2, 'Susan': 1}