0

I have a nested dictionary like

{  'A' : { 100 : [ 'apple' , 'mango'] , 
            98 : [ 'banana', 'grapes'], 
           101 : [ 'melon', 'peach'] }  , 
  'Bb' : {  16 : [ 'a' , 'm'] , 
            67 : [ 'b', 's'], 
             0 : [ 'm', 'p'] } }

I want the dictionary to be arranged according to the numbers..like 98 , 100 and 101 in ascended order.

7
  • 7
    Dictionaries are not ordered data types, therefore can not be sorted. Commented Jul 18, 2018 at 5:25
  • 1
    Also, what do you imagine would be a result of sorting a nested structure? e.g. {"A": { 1: [], 3: [] }, "B": { 2: [] } }? Because I really can't figure out what kind of result you expect. Commented Jul 18, 2018 at 5:27
  • 1
    Perhaps you can shed some light on why you want to sort the dictionary? Do you want to output it in a sorted way? Commented Jul 18, 2018 at 5:30
  • 1
    (@BcK: You could sort a dictionary by transforming it into a collections.OrderedDict, though.) Commented Jul 18, 2018 at 5:30
  • 1
    FWIW, dictionaries in Python 3.7 now retain insertion order. Commented Jul 18, 2018 at 5:37

1 Answer 1

3

Try the following. First, iterate your dictionary and create a OrderedDict sorting the elements by key, and then create another OrderedDictionary using your outter dictionary:

d = { 'A' : { 100 : [ 'apple' , 'mango'] , 98: [ 'banana', 'grapes'], 101: ['melon', 'peach'] }  , 'Bb' :  { 16 : [ 'a' , 'm'] , 67: [ 'b', 's'], 0: ['m', 'p'] }  }
for key, value in d.items():
    d[key] = OrderedDict(sorted(value.items()))
d = OrderedDict(sorted(d.items()))

Output:

print(d)
OrderedDict([('A',
              OrderedDict([(98, ['banana', 'grapes']),
                           (100, ['apple', 'mango']),
                           (101, ['melon', 'peach'])])),
             ('Bb',
              OrderedDict([(0, ['m', 'p']),
                           (16, ['a', 'm']),
                           (67, ['b', 's'])]))])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.