1

When the user gives input it puts it in a dictionary. When nothing or blanc is filled in it code should stop and give all the inputs + occurences in the dictionary.

nummer = 1
def namen(namen):
    var = 1

    key = {}

    while var == 1:
        invoer = input('Volgende naam: ')
        if invoer != '':
            global nummer
            key[nummer] = invoer
            nummer +=1
        else:

            return key
            break

hey = (namen(5))

I tried counter and a for loop but that doesn't work. So for instance if input = `h, d, d, hh, a, s

`it should give `
h=1
d=2
hh=1
a=1
s=1`
54m
  • 719
  • 2
  • 7
  • 18

3 Answers3

1

Here's a reworking of your code that does what I think you are trying to achieve. It takes advantage of Counter from the standard collections module.

from collections import Counter

def namen():

    bedragen = Counter()

    while True:
        invoer = input('Volgende naam: ')
        if invoer == '':
            break
        bedragen[invoer] += 1
    return bedragen


hey = namen()
jez
  • 14,867
  • 5
  • 37
  • 64
0

This looks working..

key = {}

while True:
    uinp = raw_input('Write something: ')
    print uinp
    if len(uinp) == 0:
        break

    try:
        key[uinp] += 1
    except:
        key[uinp] = 1

print key

is this what you wanted?

Riccardo Petraglia
  • 1,943
  • 1
  • 13
  • 25
0

If the input is guaranteed to be separated by , (comma-space), you can use the following snippet with collections.Counter:

>>> import collections
>>> input = 'h, d, d, hh, a, s'
>>> collections.Counter(input.split(', '))
Counter({'d': 2, 'a': 1, 'hh': 1, 's': 1, 'h': 1})

To get your specific formatting, you can do the following:

>>> for k, v in collections.Counter(input.split(', ')).items():
...     print ('{}={}'.format(k, v))
...
a=1
hh=1
s=1
d=2
h=1

If you just want to delimit with commas and ignore other whitespace, you can replace input.split(', ') in any of the above snippets with [i.strip() for i in input.split(',')].

brianpck
  • 8,084
  • 1
  • 22
  • 33