0

I have a string consisting of space separated nos : 5 4 4 2 2 8.

I want to construct a dictionary out of this which would have the no of times each no appear in the above string .

I first try to construct a list out of the above input line by the below code :

nos = input().split(" ")
print (nos)

Now i want to iterate through the above list using dict comprehension to create the dictionary .

How can i do the same , can someone please help?

Praveen
  • 8,945
  • 4
  • 31
  • 49
Subhayan Bhattacharya
  • 5,407
  • 7
  • 42
  • 60

5 Answers5

3

You asked for a dict comp so that's what I'll show here, but I also agree that this is a place to use a Counter or derivative:

nos = input().split()
my_dict = {k: nos.count(k) for k in set(nos)}

It works by first finding the unique elements (by creating a set) then using the list count() method for every unique element of the input list.

smassey
  • 5,875
  • 24
  • 37
1
from collections import Counter
Counter('5 4 4 2 2 8'.split(' '))
Andrey
  • 59,039
  • 12
  • 119
  • 163
1

You can use collections.Counter:

from collections import Counter

n = "5 4 4 2 2 8"
n = n.split(" ")

occurrences = Counter(n)

If you don't want to import anything you can use count:

n = "5 4 4 2 2 8"
n = n.split(" ")

unique = set(n)

occurences = {i:n.count(i) for i in unique}

Output:

{'4': 2, '2': 2, '5': 1, '8': 1}
Farhan.K
  • 3,425
  • 2
  • 15
  • 26
1

Try using Counter;

>>> import collections
>>> input_str = '5 4 4 2 2 8'
>>> dict(collections.Counter(input_str.split(" ")))
{'4': 2, '2': 2, '8': 1, '5': 1}
Praveen
  • 8,945
  • 4
  • 31
  • 49
0
str1 = '5 4 4 2 2 8'

function used to create a dictionary :

def func_dict(i, dict):
  dict[i] = dict.get(i, 0) + 1
  return dict

d = dict()
( [ func_dict(i, d) for i in str1.split() ] )
print "d :", d
Gurdyal
  • 161
  • 2
  • 2
  • 11