简体   繁体   中英

How to make a one key for all values in dictonary python

I have a list:

List_ = ["Peter", "Peter", "Susan"]

I want to make a dictonary like this:

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)

It is printing only last ones:

{"Name": "Susan", "Count": 1}

As noted in comments, a dictionary can only have each key once .

You may want a list of dictionaries , built with help from collections.Counter and a list comprehension.

>>> 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}]

In addition to using collections.Counter you could use a 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}]

Here is the implementation that you can use according to what you would like:

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)

And output will be:

[{'Name': 'Peter', 'Count': 2}, {'Name': 'Susan', 'Count': 1}]

You can use the following code to achieve what you are trying to do.

List_ = ["Peter", "Peter", "Susan"]

dict_ = {}
for name in List_:
    if name in dict_:
        dict_[name] += 1
    else:
        dict_[name] = 1

print(dict_)

Generates the following output where key is the name and value is the count.

{'Peter': 2, 'Susan': 1}

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