1

suppose I have a dictionary with some keys.

I can access a key by name:

my_dict[my_key]

Now suppose I want to access one of the keys (no matter which). I could just list the keys and take the first one.

So the access to this key will look like

my_dict[my_dict.keys()[0]]

However I'm wondering if I can just directly access the "first" element of a dictionary by just indexing. I know "first" doesn't make sense, but I just mean the first key that my_dict.keys() would return.

Something like:

my_dict[0]

But here instead of taking "the key 0" I want this 0 to be an index.

Why I want this:

Basically all keys have the same structure inside, and I need to get this structure, so any of the keys will work.

jamylak
  • 128,818
  • 30
  • 231
  • 230

1 Answers1

0

Not sure you may find another trick than what you mention i.e. my_dict[my_dict.keys()[0]].

As dictionaries are unordered, I'm not quite sure though what an index would mean.

Now, you may want to put that in a pandas.DataFrame() using :

import pandas as pd
df = pd.DataFrame.from_dict(my_dict)

Which handles indices.

Now you can indeed do :

> df.iloc[0]
arnaud
  • 3,293
  • 1
  • 10
  • 27
  • This question never mentions `pandas` and does not have `pandas` tag – jamylak Feb 16 '18 at 10:14
  • That's right but I thought maybe user doesn't know / didn't think of it. In my opinion that seems like a good candidate when considering dicts with index. – arnaud Feb 16 '18 at 10:15