Tyler L
Tyler L

Reputation: 845

Access the nth element of an object in Python

Here's the json

{u'skeleton_horde': 2, u'baby_dragon': 3, u'valkyrie': 5, u'chr_witch': 1, u'lightning': 1, u'order_volley': 6, u'building_inferno': 3, u'battle_ram': 2}

I'm trying to make the list look like this

skeleton_horde baby_dragon valkyrie lightning order_volley building_inferno

Here's the python

print(x['right']['troops'])

There's surprisingly no documentation on how to get the n element of an object (not array). I tried:

print(x['right']['troops'][1])

but it doesn't work.

Upvotes: 0

Views: 1218

Answers (3)

SwiftsNamesake
SwiftsNamesake

Reputation: 1578

There's no way of getting the nth item in a dictionary (perhaps you've conflated Python dicts with JavaScript objects) for the simple reason that they are unordered.

There is however a type of dictionary that does maintain the order of its keys, aptly named OrderedDict.

Solution

As another commenter pointed out, there is a solution to your problem, but it still won't give you the keys in the order of definition:

' '.join(obj['right']['troops'])

Note

In a recent version of CPython (3.6), dictionary keys are indeed ordered. I'm not sure if I'd rely on implementation-specific behaviour, or whether you even need to order the keys in this case, but it's good to know. Props to @ScottColby for pointing this out to me!

Upvotes: 2

Scott Colby
Scott Colby

Reputation: 1430

You want to use dict.keys() to a get a list* of the key values of the dict:

print(list(x['right']['troops'].keys()))

*It's actually a view, in Python 3. It would be a list in Python 2.

Upvotes: 2

Andrew Lei
Andrew Lei

Reputation: 335

First you want to extract the keys:

x['right']['troops']

Then you want to join them with spaces interspersed

' '.join(x['right']['troops'])

This will be in a different order than what you have, though, since Python dictionaries are unordered.

Upvotes: 2

Related Questions