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

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • In Python that first data structure is called a [dictionary](https://docs.python.org/3/tutorial/datastructures.html#dictionaries). 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`](https://docs.python.org/3/library/collections.html#collections.defaultdict) can provide a concise solution. – kungphu Apr 20 '19 at 04:39

3 Answers3

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}
ggorlen
  • 44,755
  • 7
  • 76
  • 106
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)
zedfoxus
  • 35,121
  • 5
  • 64
  • 63
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}
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40