简体   繁体   中英

How do I access items of a dictionary using items from a tuple?

If I have a tuple of tuples:

cyc = (('a-b', 'b-a'), ('a-c', 'c-a'), ('b-c', 'c-b'))

and a dictionary of dictionaries:

data = {'a-b': {'x': 1, 'y': 2},
        'b-a': {'x': 3, 'y': 4},
        'a-c': {'x': 5, 'y': 6},
        'c-a': {'x': 7, 'y': 8},
        'b-c': {'x': 9, 'y': 10},
        'c-b': {'x': 11, 'y': 12}}

How do I access elements of the dictionary using elements of the tuple?

For example if i simply want to print an element:

print(data[cyc[1[0['x']]]])

I taught this would return 5.

Instead this gives me the error message:

''TypeError: 'int' object is not subscriptable''

When you're accessing nested items, you don't nest the indexes, you append them.

cyc[1] == ('a-c', 'c-a')

That means

cyc[1][0] == 'a-c'

To use that as the index in a dictionary, you write

data[cyc[1][0]]

and then to get the x index from that nested dictionary, you append ['x'] :

data[cyc[1][0]]['x']

When you write something like 0['x'] it means to index the 0 value, which doesn't make any sense.

Inside [] you put the key that is being accessed. If you want an item from inside that returned value, you put another [] after that:

print(data[cyc[1][0]]['x'])

Takes from the dictionary data the value at key cyc[1][0] , which is the element 0 inside the element 1 inside cyc. From that value, which is another dictionary, take the value at key 'x'

Here is the sequence of sub-expressions you were hoping to go through:

>>> cyc[1]
('a-c', 'c-a')
>>> cyc[1][0]
'a-c'
>>> data[cyc[1][0]]
{'x': 5, 'y': 5}
>>> data[cyc[1][0]]['x']
5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM