Home > Blockchain >  Get tuple of values from nested dict
Get tuple of values from nested dict

Time:12-23

I'm trying to create a python script that goes through a dict with a structure similar to:

structure = {
    'key1' : {'keyA' : 'valueA1', 'keyB' : {'keyC' : 'valueC1', 'keyD, 'valueD1'} },
    'key2' : {'keyA' : 'valueA2', 'keyB' : {'keyC' : 'valueC2', 'keyD, 'valueD2'}},
    'key3' : {'keyA' : 'valueA3', 'keyB' : {'keyC' : 'valueC3', 'keyD, 'valueD3'}}
}

and returns a tuple, lets say, with every 'valueDX' element where X is 1, 2 or 3. I mean, return a tuple like

(valueD1, valueD2, valueD3)

I tried doing

my_list = []
for x in structure.values():
    my_list.append(x['keyB'].values()['keyD'])

But I have the following error:

TypeError: 'dict_keys' object is not subscriptable

CodePudding user response:

   your_list=[]
   for x1 in structure.values():
      try:
         your_list.append(x1['keyB']['keyD'])
      except:
         pass   # it better use try when dealing dict or unknown structure
   return your_list

you don't have use values() methods to get specific value. it for dict values iteration.

CodePudding user response:

can do it in one liner as long as the keys are the same with every dict and always exist:

my_list = [v['keyB']['keyD'] for k,v in structure.items()]

CodePudding user response:

tuple([structure[key]["keyB"]["keyD"] for key in structure.keys()])
# ('valueD1', 'valueD2', 'valueD3')

CodePudding user response:

you can use dict.get()

your_list=[]
for x1 in structure.values():
    your_list.append(x1.get('keyB').get('keyD'))

print(tuple(your_list))

CodePudding user response:

From the doc dict-methods like values, keys return a dictionary-view-objects. This doesn't provide a direct access to its content as for list, tuple, ... but only iterate through it.

d = {1: 'A'}
print(type(d.values()))
#dictionary-view-objects

# casting the view
print(list(d.values())[0])
#A

# direct access to values of the view raise an error 
try:
   d.values()[0]
except TypeError:
   pass # TypeError: 'dict_keys' object is not subscriptable

Here a possible solution

structure = {
    'key1' : {'keyA' : 'valueA1', 'keyB' : {'keyC' : 'valueC1', 'keyD': 'valueD1'} },
    'key2' : {'keyA' : 'valueA2', 'keyB' : {'keyC' : 'valueC2', 'keyD': 'valueD2'}},
    'key3' : {'keyA' : 'valueA3', 'keyB' : {'keyC' : 'valueC3', 'keyD': 'valueD3'}}
}


my_list = []
key_levels = 'keyB', 'keyD'

for key_i in structure:
    d = structure[key_i]
    for key in key_levels:
        d = d[key]
    my_list.append(d)

my_list = tuple(my_list)
print(my_list)
  • Related