How to sort items from a list using two different values?

Asked

Viewed 61 times

0

I have a list, which contains several values, each group of values corresponds to an audio of a language, however I am not able to sort using two conditions.

audio_list = [{640: 640, 'lang': u'en', 'language': 'English', 'lang_code': 'en', 'bitrate': 640, 'size': 226600396}, {448: 448, 'lang': u'en', 'language': 'English', 'lang_code': 'en', 'bitrate': 448, 'size': 159037132}, {384: 384, 'lang': u'en', 'language': 'English', 'lang_code': 'en', 'bitrate': 384, 'size': 136516042}, {384: 384, 'lang': u'en', 'language': 'English', 'lang_code': 'en', 'bitrate': 384, 'size': 136516044}, {256: 256, 'lang': u'en', 'language': 'English', 'lang_code': 'en', 'bitrate': 256, 'size': 91473868}, {192: 192, 'lang': u'en', 'language': 'English', 'lang_code': 'en', 'bitrate': 192, 'size': 68952780}, {128: 128, 'lang': u'en', 'language': 'English', 'lang_code': 'en', 'bitrate': 128, 'size': 46431692}, {128: 128, 'lang': u'pt-BR', 'language': 'Brazilian', 'lang_code': 'pt-BR', 'bitrate': 128, 'size': 46431692}, {96: 96, 'lang': u'en', 'language': 'English', 'lang_code': 'en', 'bitrate': 96, 'size': 35171148}, {96: 96, 'lang': u'pt-BR', 'language': 'Brazilian', 'lang_code': 'pt-BR', 'bitrate': 96, 'size': 35171148}]

language = ['pt-BR', 'en']

for idx, language_code in enumerate(language):
    max_audio = audio_list[ idx ]
    lang_bitrate = max_audio.get('bitrate')
    lang_name = max_audio.get('language')
    print(lang_name + " - " + str(lang_bitrate))

When I run the above code, I get the following result:

English - 640

English - 448

However I should get the following result, sorted by the type of audio that comes first on language and by bitrate:

Brazilian - 128

English - 640

How could I receive the above result, ordered by bitrate of audios in audio_list, and in the order of language ?

1 answer

2


If I understood and/or implemented correctly, the result will be different from what Oce presents, I will order the list of dictionaries, there is only vc adapt to your context:

# Ordenando
audio_sorted = sorted(audio_list, key=lambda k: (list(k.keys())[0],\
k['language'], k['bitrate']))

# Apresentando os 3 primeiros resultados:
audio_sorted[:3]
[{96: 96,
  'lang': 'pt-BR',
  'language': 'Brazilian',
  'lang_code': 'pt-BR',
  'bitrate': 96,
  'size': 35171148},
 {96: 96,
  'lang': 'en',
  'language': 'English',
  'lang_code': 'en',
  'bitrate': 96,
  'size': 35171148},
 {128: 128,
  'lang': 'pt-BR',
  'language': 'Brazilian',
  'lang_code': 'pt-BR',
  'bitrate': 128,
  'size': 46431692}]

See working on repl it..

Observing:
You can vary the "Keys" to get the desired result.

Browser other questions tagged

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