1

I have a dictionary structure like the one shown below and I want to extract the "EV=5.0" part from it. Just the first instance of it that is.

my_dict = {('zone1', 'pcomp100002', '33x75'): {('Dummy', 'EV=5.0', -5.0, -5.0, -5.0): 68.49582}, ('zone1', 'pcomp100004', '33x75'): {('Dummy', 'EV=5.0', -5.0, -5.0, -5.0): 37.59079}}

Note that the only thing I know is the structure of the dict but not the actual master keys (e.g., ('zone1', 'pcomp100002', '33x75')) or sub keys (e.g., ('Dummy', 'EV=5.0', -5.0, -5.0, -5.0).

In other words, I know the location of the information I want to retrieve. Present in all sub keys in position 1.

I came up with two ways to do it but I like neither of them:

# method 1 - unreadable
print(list(list(my_dict.values())[0].keys())[0][1])

# method 2 - two loops broken in their first iteration
for i in a.values():
    for j in i:
        print(j[1])
        break
    break

Converting the whole dict to string and seraching for "EV=" also occured to me but buit that was the ugliest thought I made in a long time.

Is there a better way that i am missing?

Ma0
  • 15,057
  • 4
  • 35
  • 65
  • How about `[data[1] for key in my_dict.values() for data in key]`? – styvane Dec 14 '16 at 10:26
  • The actual dictionary is much much longer than the sample shown here so your list comprehension would not be very efficient. But if coupled with `next` we might be going somewhere – Ma0 Dec 14 '16 at 10:28
  • `next` will only return the first value. I don't know if that is what you want, that is why I posted as comment. – styvane Dec 14 '16 at 10:33
  • @Styvane It was not very clear from the question. One had to look at my code to realise it was only the first instance of it I was after. I updated the question. Sorry. – Ma0 Dec 14 '16 at 10:36

1 Answers1

3

You could turn the version 2 to generator expression and use next:

>>> my_dict = {('zone1', 'pcomp100002', '33x75'): {('Dummy', 'EV=5.0', -5.0, -5.0, -5.0): 68.49582}, ('zone1', 'pcomp100004', '33x75'): {('Dummy', 'EV=5.0', -5.0, -5.0, -5.0): 37.59079}}
>>> next(k[1] for v in my_dict.values() for k in v)
'EV=5.0'
niemmi
  • 17,113
  • 7
  • 35
  • 42