-3

For example from dictionary

{"Name": "Mark","country": "England", "Age":15,

"Name": "Tom","country": "Poland", "Age":10,

"Name": "Sam","country": "USA", "Age":19,

"Name": "Bob","country": "Italy", "Age":17}

I want to get

{"Name": "Tom","country": "Poland", "Age":10,

"Name": "Mark","country": "England", "Age":15,

"Name": "Bob","country": "Italy", "Age":17,

"Name": "Sam","country": "USA", "Age":19,}

Code like this is not helping

for key, value in sorted(dict.items(), key=lambda item: int(item[0]))
2e0byo
  • 5,305
  • 1
  • 6
  • 26
Steve
  • 9
  • 3

1 Answers1

1

Assuming you meant to have a list of dicts like this:

a = [{"Name": "Tom","country": "Poland", "Age":10},
     {"Name": "Mark","country": "England", "Age":15},
     {"Name": "Bob","country": "Italy", "Age":17},
     {"Name": "Sam","country": "USA", "Age":19}]

The most obvious answer with this dataset would be:

sorted(a, key=lambda x:x["Age"])

For the more general case of sorting on all integer values you could use something like:

sorted(a, key=lambda x: sum(v for v in x.values() if isinstance(v, int)))

although depending on your usecase checking for int might be too narrow a criterion. This solution first sums up all ints in the dict (v for v in x.values() if isinstance(v, int)) and then sorts on that sum.

2e0byo
  • 5,305
  • 1
  • 6
  • 26