A problem with keys, values, and dictionaries

You’ll see several times in this code something like this: name_of_dict[name_of_key][0] What does the last index do? (In this case its ‘[0]’)

https://www.codecademy.com/paths/computer-science/tracks/cspath-graph-search-algorithms/modules/cspath-advanced-graph-search-algorithms/lessons/a-star-python/exercises/a-star-python-pathway

If your dictionary key contained a list, or some other data structure, you would reference it that way.

For example,

some_stuff = {
    'cheese' : ['cheddar','stilton'],
    'meat' : ['bacon','lamb'],
    'veggies' : ['carrot','potato']
}

then some_stuff['meat'][0] = 'bacon'.

2 Likes

okay, so it gets the first index of the value of the key. Cool stuff

Yes, provided that the contents of that key are a type which can be indexed. If the value was an int, for example, you would get an error.

some_stuff = {
    'cheese' : ['cheddar','stilton'],
    'meat' : ['bacon','lamb'],
    'veggies' : ['carrot','potato'],
    'numerical' : 13,
}

print(some_stuff['numerical'][0])

Traceback (most recent call last):
  File "subscripting.py", line 8, in <module>
    print(some_stuff['numerical'][0])
TypeError: 'int' object is not subscriptable

>>>