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.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Sona
  • 27
  • 3
  • 7
    Dictionaries are not ordered data types, therefore can not be sorted. – BcK Jul 18 '18 at 05: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. – Amadan Jul 18 '18 at 05: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? – IonicSolutions Jul 18 '18 at 05:30
  • 1
    (@BcK: You could sort a dictionary by transforming it into a `collections.OrderedDict`, though.) – Amadan Jul 18 '18 at 05:30
  • Dictionaries cannot be sorted as they are not ordered. – Abhishek Chandel Jul 18 '18 at 05:35
  • 1
    FWIW, [dictionaries in Python 3.7](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) now retain insertion order. – andrew_reece Jul 18 '18 at 05:37
  • _to be arranged_ .. for what purpose? As earlier comments pointed out, dictionarys are not sorted. From 3.6.something on the CPython implementation will keep the keys ordered in the order they were inserted. This is an implementation detail , and varies over different implementations (see [are python dicts ordered in 3.6](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6) ). For output you can iterate over sorted keys and print them - add what exactly your expected output would be like to be helped here. In 3.7 they are insert ordered as lang feature. – Patrick Artner Jul 18 '18 at 05:42

1 Answers1

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'])]))])
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228