Ordering dictionary by obtaining values

Asked

Viewed 50 times

2

I have the following function that I have done which is this :

def funcao(elemento):
    x = []
    for i in grafico:
            timestring = i["CrimeTime"]
            x.append(timestring)
    x= sorted(x)

    y= Counter(x).values()
    return x,y

And what you give me is :

(['16:40:00', '16:45:00', '17:30:00', '18:30:00', '18:38:00', '20:00:00', '21:30:00', '21:30:00', '21:51:00'], [1, 1, 2, 1, 1, 1, 1, 1])

Being what you should give me is :

Código :
(['16:40:00', '16:45:00', '17:30:00', '18:30:00', '18:30:00', '20:00:00', '21:30:00', '21:30:00', '21:51:00'], [1, 1, 1, 2 , 1,2, 1])

The goal is to get the ordered hours that gives correct ,and the number of times each hour repeats , and the values are well , are not correctly positioned( may have to do with the fact to fetch the values to dictionary) but I don’t see how I get the correctly ordered values

1 answer

1

Dude,

what’s happening to my view is, when you call Counter(x) a dictionary is being created, using the values that were in your list as keys and the number of times that value appears in the list as the value.

When you call .values() in the dictionary that was created, it returns the values that are present for each key, but the dictionary does not guarantee the ordering.

If you make key access by key you will see that the values are correct.

def funcao(elemento):
    x = []
    for i in grafico:
        timestring = i["CrimeTime"]
        x.append(timestring)
    x = sorted(x)        
    unique_x = sorted(set(x)) #remove os valores duplicados de x mantendo a ordenação
    count_x = Counter(x)
    y = [count_x[value] for value in unique_x]

    return x,y

I don’t know what your real needs are, but I might just return the dictionary, which already contains all the desired information.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.