M
M
maksam072021-11-17 00:34:13
Python
maksam07, 2021-11-17 00:34:13

How to sort the dictionary first by keys, and then by each key a list?

Goodnight. Suppose we have the following dictionary:

{
  'foo': [
    'val2',
    'val1',
    'val3'
  ],
  'bar': [
    'b1'
  ],
  'mem': [
    'ab1c',
    'b1ca'
  ]
}

Final dictionary:
{
  'bar': [
    'b1'
  ],
  'foo': [
    'val1',
    'val2',
    'val3'
  ],
  'mem': [
    'ab1c',
    'b1ca'
  ]
}


I hope I manually sorted the final one correctly. That is, first the keys in alphabetical order, then in each key the list in alphabetical order

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wispik, 2021-11-17
@maksam07

a = {
  'foo': [
    'val2',
    'val1',
    'val3'
  ],
  'bar': [
    'b1'
  ],
  'mem': [
    'ab1c',
    'b1ca'
  ]
}


b = dict([(x[0], sorted(x[1])) for x in sorted(a.items())])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question