0

I am doing my homework but when I tried to use dict to count the numbers, I found that I cannot get exact value from the list...

def get_data(openfile):
    totalcount = 0
    digit_count = {d:0 for d in '123456789'}
    for line in openfile:
        line = line.strip()
        if int(line[0]) != 0 and line[0].isdigit():
            first_digit = line[0]
            totalcount += 1
            digit_count[first_digit] += 1
    print(digit_count)
    contents = []
    for data in digit_count:
        contents.append(data)
    print(contents)

Then I used print to see what is in the 'digit_count' and 'contents'.

in the digit_count:

{'5': 89, '3': 203, '7': 79, '8': 77, '1': 500, '9': 69, '2': 304, '6': 70, '4': 140}

in the content:

['5', '3', '7', '8', '1', '9', '2', '6', '4']

Is that aviliable to get the count numbers from the digit_count..? any ideas? The numbers I want to get such as 89,203,79...

Robin
  • 13
  • 5

5 Answers5

1

You want to get the values from your dictionary; just use the .values() method.

vals = digit_count.values()
Moe Chughtai
  • 384
  • 2
  • 13
0

change your code to:

 for data in digit_count:
            contents.append(digit_count[data])
Adam Lyu
  • 431
  • 1
  • 5
  • 17
0

Instead of this:

for data in digit_count:
    contents.append(data)

You can use:

contents = digit_count.values()
Armen Halajyan
  • 87
  • 1
  • 2
  • 9
0

print key

digit_count.keys()

print value

digit_count.values()
galaxyan
  • 5,944
  • 2
  • 19
  • 43
0

Replace

  contents = []
  for data in digit_count:
      contents.append(data)
  print(contents)

with

  contents = dict(digit_count.items())
  print(contents)
dmitryro
  • 3,463
  • 2
  • 20
  • 28