0

The example marked as duplicate does not address nested dictionaries. Although i tried the example in the duplicate that uses collections.OrderedDict() but it either gave list index out of range or doesnt print anything at all.

The data looks similar to this:

[  {
     "name":"frog",
     "age":33,
     "color":"green",
     "weight":86,
     "can_jump": true,
     --- other data and so on ---
  },

  {
    -- other data too ---
  }
]

and here is the code i used to retrieve the first four data and store it in the results list.

i = 0
while i < len(data_file):
    key = ["name", "age", "color", "weight"]
    results = []
    for x in data_file[i]:
        results.append(data_file[i][x])
    j = 0
    while j < 4:
        print("{}: {}".format(key[j], results[j]))
        j+=1
    print()
    i+=1

but when i print out the final ,

results they display randomly like e.g.

name: 33
age:86
color: true
weight: green
tushortz
  • 3,697
  • 2
  • 18
  • 31
  • dicts are unordered, you need an OrderedDict shown in th dupe – Padraic Cunningham Aug 08 '15 at 14:11
  • 1
    I assume that `data_file[i]` is a dict. You can put your `key = ["name", "age", "color", "weight"]` before the `while` loop; get rid of that `results.append()` loop, and that `j` stuff; and then just do `for k in key:` `print("{}: {}".format(k, data_file[i][k]))`. – PM 2Ring Aug 08 '15 at 16:20
  • @PM2Ring It worked now. I'm highly grateful – tushortz Aug 08 '15 at 17:17
  • Generic dictionaries don't preserve order.However you can use sort with item-getter to convert dictionary into a tuple sorted by keys – Aditya Aug 08 '15 at 17:18

0 Answers0