Scroll through a Dict until it is empty in Python

Asked

Viewed 3,050 times

0

How do I go through while a list of values and keys is non-zero, just add the values (values()) in a list? The code I have is this:

hey = ['item1', 'item2', 'item3', 'item4']
print("hey", hey)
lol = [32, 54, 56, 64]
print("lol", lol)
lil = dict(zip(lol, hey))
print("lil: ",lil)
pop = list(zip(lil.values(), lil.keys()))
print("pop sem ordenar: ", pop)

sorted(pop, reverse=True)
print("pop ordenado: ", pop)

#for i in lil:
     #  print("i: ",i)
     #  print("lil[i]: ", lil[i])

max_value = max(pop)

print("max_value: ", max_value)
novo_lil = lil[max_value[1]]
del lil[max_value[1]]
print("lil nova: ",lil)

I tried to do it, but it didn’t work:

hey = ['item1', 'item2', 'item3', 'item4']
print("hey", hey)
lol = [32, 54, 56, 64]
print("lol", lol)
lil = dict(zip(lol, hey))
print("lil: ",lil)
pop = list(zip(lil.values(), lil.keys()))
print("pop sem ordenar: ", pop)

sorted(pop, reverse=True)
print("pop ordenado: ", pop)

#for i in lil:
     #  print("i: ",i)
     #  print("lil[i]: ", lil[i])

max_value = max(pop)

while not(lil[max_value[1]]):
    print("max_value: ", max_value)
    novo_lil = lil[max_value[1]]
    del lil[max_value[1]]
    print("lil nova: ",lil)

Can someone help me? What I’m actually doing is ordering a Dict and then adding only its values to a list, that’s all.

  • 2

    I didn’t understand your doubt, but I realized that you are using the Sorted function in the wrong way, you should do so "pop = Sorted(pop,Reverse=True)". If you can explain the doubt better.

  • Okay @Paulohenrirdoso, it’s like this: I have two lists. Each value of hey corresponds to a value of lol. Soon 'item1' has value 32, 'item2' has value 54 and so on! I need to sort the list hey based on the list lol in descending form, so lol stay: [64, 56, 54, 32] but the list hey should also be ordered corresponding with each value of lol: hey = ['Item4', 'item3', 'item2', 'item1']

  • The way I found my friend @Miguel was to relate them through a Dict as it is done in: Lil = Dict(zip(lol, hey))

  • So I turn this Dict of mine into a list and I order it, like you corrected it. Since it is not possible to order a Dict, I thought to take the higher value of Dict and add it in order in a list, but only its values()

  • So that at the end I have hey = ['Item4', 'item3', 'item2', 'item1'] ordered based on the lol list, I managed to explain?

  • It’s just that it’s a little hard to really explain, I apologize for that.

  • I don’t know if I understand yet, but your problem seems to be the fact that the dictionary is not ordered, so you can use the Ordered Dict of the Collections library. But see if these two lines of code after sorting the "pop" list solve your problem :for i in range(Len(hey)): hey[i] = pop[i][0]

  • please pot, answer the question - ("statement"). Currently you have nothing in common with the problem stated.

Show 3 more comments

2 answers

4

Wow - - too complacent for something that looks very simple in Python.

Dictionaries have the methods keys, valuesand items that allow access to its members, and the powerful list-comprehension construct, which lets you apply any expression on each item of a sequence to generate a list.

So just do it:

hey = ['item1', 'item2', 'item3', 'item4']
lol = [32, 54, 56, 64]

dct = dict(zip(lol, hey))
result = [valor for chave, valor in sorted(dct.items(), reverse=True)]

Where dct is a dictionary that relates the two lists, as you already did - then we go through all the items in that dictionary already sorted by the key in the call to "Sorted" - as you want in descending order, we use the "Reverse". And from each item, we take the second value - which is the associated value in the original first list.

0

To sort one list according to the other I developed the following solution:

hey = ['item1', 'item2', 'item3', 'item4']
lol = [32, 54, 56, 64]

''' vamos cria uma lista de transposição com a posição original
e a nova posição do item. '''
transposicao = []
for posicao_nova, i in enumerate(sorted(lol, reverse=True)):
    posicao_original = lol.index(i)
    transposicao.append([posicao_nova, posicao_original])

# após guardar as posições, efetivamente alteramos a lista lol
lol = sorted(lol, reverse=True)

# agora utilizamos a lista de transposição para reordenar a lista hey
nova_hey = []
for i in transposicao:
    nova_hey.append(hey[i[1]])

hey = nova_hey

print(hey, lol)

The result will be as desired: ['Item4', 'item3', 'item2', 'item1'] [64, 56, 54, 32]

A simpler and more "pythonica version":

from operator import itemgetter

hey = ['item1', 'item2', 'item3', 'item4']
lol = [32, 54, 56, 64]

# junta as listas e ordena de acordo com os valors da segunda lista     (lol no caso)
ordena_junto = sorted(list(zip(hey, lol)), key=itemgetter(1), reverse=True)

# extrai as listas ordernadas
hey, lol = zip(*ordena_junto)
print(hey, lol)

Result: ('Item4', 'item3', 'item2', 'item1') (64, 56, 54, 32)

I hope you helped solve your problem.

Browser other questions tagged

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