0

I want to make array object like this:

{'book1':3, 'book2':4, 'book3':5}

from an array like this

['book1', 'book1', 'book1', 'book2', 'book2', 'book2', 
'book2', 'book3', 'book3', 'book3', 'book3', 'book3']

How to do that? my idea is looping, but dont know to count the same value

*sorry for bad explanation

1
  • In Python that first data structure is called a dictionary. Looping is certainly a valid way to accomplish what you want to do. I'd suggest reading up on dictionaries, trying it out, and updating this with your code if you have a specific question or problem. Note that it's not necessary but using defaultdict can provide a concise solution. Commented Apr 20, 2019 at 4:39

3 Answers 3

2

collections.Counter is a handy builtin for this exact task:

from collections import Counter

lst = ['book1', 'book1', 'book1', 'book2', 'book2', 'book2', 'book2', 'book3', 'book3', 'book3', 'book3', 'book3']
print(dict(Counter(lst)))

Output:

{'book1': 3, 'book2': 4, 'book3': 5}
Sign up to request clarification or add additional context in comments.

Comments

0

You could do something like this:

arr = ['book1', 'book1', 'book1', 'book2', 'book2', 'book2', 'book2', 'book3', 'book3', 'book3', 'book3', 'book3']

final = {}

# loop through each item in the array
# if it is NOT found in the dictionary, put it
# in the dictionary and give it a count of 1
# if it IS found in the dictionary, increment its value
for x in arr:
    if x in final:
        final[x] += 1
    else:
        final[x] = 1

print(final)

Comments

0

You can also use collections.Counter, which is made for exactly such thing.

from collections import Counter

li =['book1', 'book1', 'book1', 'book2', 'book2', 'book2', 'book2', 'book3', 'book3', 'book3', 'book3', 'book3']
print(dict(Counter(li)))
#{'book1': 3, 'book2': 4, 'book3': 5}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.