简体   繁体   中英

Iterating over a list and putting the values in a dictionary reflects only last element

I have the following code. The objective is to count the number of elements in the list and put it in a dictionary format.

My code is as follows

from collections import Counter

laptop_count={}

lap_list=['Dell','Mac','ASUS','HP','Dell','Mac','Dell','Lenovo']
lap_dict=dict(Counter(lap_list))

for key,value in lap_dict.items():
    laptop_count["laptop"]= key
    laptop_count["count"]= value

print(laptop_count)

The above code result in output

{'laptop': 'Lenovo', 'Count': 1}

Expected output is

{'laptop':'Dell', 'count':3, 'laptop':'Mac', 'count':2, 'laptop':'Asus', 'count':1, 'laptop':'HP', 'count':1, 'laptop':'Lenovo','count':1}

I am not able to figure what is going wrong in the code.

Your lap_dict essentially already has what you're after.

You are looping over the lap_dict and assigning the same values to laptop_count over and over, just overwriting them over each pass of the loop.

Another thing, fundamentally speaking, dictionaries cannot have multiple keys that are the same.

If you really want something "like" your desired output, you could try this:

[{'laptop':key, 'count':val} for key, val in lap_dict.items()]

result is a list:

[{'laptop': 'Dell', 'count': 3}, {'laptop': 'Mac', 'count': 2}, {'laptop': 'ASUS', 'count': 1}, {'laptop': 'HP', 'count': 1}, {'laptop': 'Lenovo', 'count': 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