Reputation: 59
I'm struggling to get single value and key pairs from a Counter in a for loop
I have the following code:
test= ["test1", "test2", "apps1", "apps2", "random"]
return collections.Counter(i[:4] for i in test)
I get the following: { "rand": 1, "test": 2, "apps": 2, }
I want to know it there a way to get these values & keys based on there position if a for loop, because I'm trying to add it to a json object for an angular app.
The JSON object I want to create looks like this,
returnObject = []
for i in range(len(collections.Counter(i[:4] for i in test))):
tempObject ={
'value': #add counter value in pos i,
'color': 'rgb(0,19,255)',
'label': #add counter key in pos i,
'order': i+1,
}
returnObject.append(tempObject)
print returnObject
Sorry I'm new to this and have tried a lot of different things, but thank you in advance for any help.
Upvotes: 0
Views: 3064
Reputation: 30268
Using range(len)
is not the canonical way to loop over a container and not very useful for a dict
type.
You can directly iterate over containers, e.g.:
counts = collections.Counter(i[:4] for i in test)
for key in counts:
print(key, counts[key])
Or more directly using .items()
:
counts = collections.Counter(i[:4] for i in test)
for key, value in counts.items():
print(key, value)
Upvotes: 1