Ashik
Ashik

Reputation: 214

How to Convert 'dict_items' Object to List

I am loading data from json files using load method and then putting the items in a new python object.

obj_1 = json.load(file)
obj_2 = obj_1.items()

When I run the code in python2, type(obj_2) is list. But when I run in python 3, type(obj_2) is 'dict_items'. Because of that when I run following code:

sorted_items = sorted (obj_2[1][1]['string'])

I'm getting this error in python 3:

TypeError: 'dict_items' object does not support indexing

In python 2 it runs fine. How can I solve this issue in python 3? I have found some related questions about this but the answers doesn't solve my particular case. I have tried to use list(obj_2) but it causes key error. json file format is something like this:

  {
    "item_1": {
      "item_2": {
        "string": 111111,
        "string": 222222,
        "string": 333333,
        ................
        ................
      },
    },
  }

I want to sort the "item_2" contents according to the keys in ascending order.

Upvotes: 3

Views: 11284

Answers (2)

simply

d = { .... }
l = list(d.items())

Upvotes: 7

Arjix
Arjix

Reputation: 158

making a for loop here is the best option i can think of.

object_list = []
for key, value in obj_2:
    entry = [key, value]
    object_list.append(entry)

that would store the key and value in a list that is inside another list.

EDIT

Found a better way to do it!

my_dict = {"hello": "there", "how": "are you?"}
my_list = [[x, y] for x, y in my_dict.items()]

# out => [['hello', 'there'], ['how', 'are you?']]

Upvotes: 1

Related Questions