Python dictionary storing integer number

I am trying to count a list of words, integers. I have a list of numbers in a csv file that I can read, which looks something like 4,245,34,99,340, ... What I am doing is trying to find a dictionary with key pairs: a value where the key is an integer value from csv file, and the value is the number of times it appears in the list. I'm not sure what I'm doing wrong here, any help would be appreciated

allCounts = dict()

rows = csv.reader(open('...csv'), delimiter=',')

    for intValue in rows:
        intVal = intValue[0]

        for intVal, numAppearances in allCounts:
             if intVal in allCounts:
                allCounts[numAppearances] = allCounts[numAppearances]+1
             else:
                allCounts[numAppearances] = 1
+3
source share
3 answers

It looks like you want to create a Counter object:
http://docs.python.org/library/collections.html#counter-objects

, CSV:
http://docs.python.org/library/csv.html

:)

, - :

csvfile = open("example.csv")
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
reader = csv.reader(csvfile, dialect)

:

c = Counter(reader)
+8

, , dict , , , , . , , dict . :

# first part stays mostly the same
rows = csv.reader(open("...csv") )

allCounts = {} 

for row in rows:
    for field in row:
        allCounts[field] = allCounts.get(field, 0) + 1

dict, , .

. . intVal, intVal, dict. , .

if . , dict, , dict. , dict.

, else , . Python , dicts,

dict. - . , , .

CSV ( ), , . CSV , . , , . , dict , .

+5

intVal = intValue[0]

intValue , . intValue = int(intValue).

. allCounts , . , , , csv.reader, . - , . , :

# Checks to see if intValue is a key in the dictionary
if intValue in allCounts:
    # If it is then we want to increment the current value
    # += 1 is the idiomatic way to do this
    allCounts[intValue] += 1
else:
    # If it is not a key, then make it a key with a value of 1
    allCounts[intValue] = 1
0
source

Source: https://habr.com/ru/post/1755363/


All Articles