Given a list of string, return a dictionary of key: value as string: number of times
时间: 2024-02-15 09:02:08 浏览: 80
To create a dictionary of key-value pairs where the key is a string from a list and the value is the number of times that string appears in the list, you can use a loop to iterate over the list and add each string to a dictionary with its count as the value. Here's an example code snippet:
```python
def count_strings(lst):
# create an empty dictionary
string_counts = {}
# iterate over the list
for string in lst:
# if the string is already in the dictionary, increment its count
if string in string_counts:
string_counts[string] += 1
# otherwise, add the string to the dictionary with a count of 1
else:
string_counts[string] = 1
# return the dictionary
return string_counts
```
You can call this function with a list of strings as an argument to get a dictionary of string counts. For example:
```python
count_strings(["apple", "banana", "apple", "orange", "banana", "pear"])
```
Output:
```
{'apple': 2, 'banana': 2, 'orange': 1, 'pear': 1}
```
阅读全文