Home > front end >  python list of dictionaries elements to be arranged based on the name of the key
python list of dictionaries elements to be arranged based on the name of the key

Time:04-10

I have tried the below list1 to arrange in a custom order ( based on the name of the key):

example each dict should be arranged in the same order of names: please see 'result'

list1 = [{"eight":8, "nine":9, "one":1, "three":3, "two":2, "four":4, "six":6, "five":5, "seven":7},
         {"eight":8, "two":2, "four":4, "six":6, "five":5, "seven":7, "nine":9, "one":1, "three":3}]

I want to get the above one into the below one: please advice:

result = [{"one":1, "two":2, "three":3, "four":4, "five":5, "six":6, "seven":7, "eight":8, "nine":9},
          {"one":1, "two":2, "three":3, "four":4, "five":5, "six":6, "seven":7, "eight":8, "nine":9}]

CodePudding user response:

I think the easiest way would be by creating an array of keys first eg:

key_names = ["one","two","three"...]

Then you you create a new variable with the keys in each array using the .keys() function on list1 eg. new_var = list1[0].keys(). Next, you loop through each key name replacing with it's preferred value (), sort the new variable in ascending / descending since they are now numbers...

CodePudding user response:

Python dictionnaries aren't meant to be ordered. To do so, you should use collections.OrderedDict. Full doc here : https://docs.python.org/3/library/collections.html#collections.OrderedDict

Then you could use a standard sorting algorithm to sort your dictonnary in any way you want.

Not than for python 3.6 and above, dictionnaries maintains insertion order by default, even though if the order is really important to you, OrderedDict are more suitable.

CodePudding user response:

This is how you'd sort a single dictionary the way you want

dict(sorted([x for x in d.items()], key=lambda x: x[1]))

and here's how you'd sort all of them in a list

[dict(sorted([x for x in d.items()], key=lambda x: x[1])) for d in ls]
  • Related