-1

How do I get the gender value?

The datetime key might be different, so I want to be able to access it no matter what the key name there is.

{'data': {'2021-01-20 01:14:47 UTC': {'gender': 2, 'goodHost': 0, }}}
aquatic7
  • 615
  • 1
  • 6
  • 19
  • 2
    Please post everything you have tried so far. – CATboardBETA Jan 20 '21 at 20:10
  • The datetime key is a string or a datetime object? Will that always the structure of the dictionary as a whole? – goalie1998 Jan 20 '21 at 20:11
  • 1
    @Sayse That other question has known keys. – superb rain Jan 20 '21 at 20:12
  • 2
    @Sayse I'm not sure the dupe is accurate. The problem here is not the nesting, but the fact that the key is very arbitrary (which seems to be a very bad design decision) – DeepSpace Jan 20 '21 at 20:12
  • [Dictionary get value without knowing the key](https://stackoverflow.com/q/33709331/1324033) – Sayse Jan 20 '21 at 20:13
  • 1
    Does this answer your question? [Dictionary get value without knowing the key](https://stackoverflow.com/questions/33709331/dictionary-get-value-without-knowing-the-key) – Asocia Jan 20 '21 at 20:13

2 Answers2

5

If you can guarantee that there will only be one datetime key ever, you could do something like:

data = my_dict['data']
item = list(data.values())[0]
print(item['gender'])

Basically, my_dict['data'].values() will return all of the values in the nested dictionary without caring what the key is. If you know there will only be one such item, you can go directly to it that way.

If you might have multiple keys in there, you can loop across the values and look for the ones that have the gender key:

for value in my_dict["data"].values():
    try:
        print(value["gender"])
    except KeyError:
        print("Didn't have a gender key so I'm skipping it.")
Kirk Strauser
  • 30,189
  • 5
  • 49
  • 65
  • There are many datetime keys :/ Here's an example with 2 {''data': {'2021-01-20 01:14:47 UTC': {'gender': 2, 'goodHost': 0, }, '2021-01-20 01:19:11 UTC': { 'gender': 1, 'goodHost': 0,}}} – aquatic7 Jan 20 '21 at 20:18
  • I'd skip `list(...)` and just iterate over `items`/`values` – DeepSpace Jan 20 '21 at 20:19
  • 1
    See the second half of that answer for how it might work if there are multiple datetime keys. Like @DeepSpace said, in that case you'd want to iterate over the values instead of strictly looking at the first one. – Kirk Strauser Jan 20 '21 at 20:21
1

Just take the first=only value.

>>> next(iter(d['data'].values()))['gender']
2
superb rain
  • 5,300
  • 2
  • 11
  • 25