简体   繁体   中英

How to access the last element in the list values in a dictionary that contain lists as values

For example:

dictionary = {'a':[3,0], 'b':[5,0]}

If I'm writing an if-statement to check whether or not the last element of the list value pairs is zero, how should I access it?

You can access the last element in a list with list_name[-1] .

Your if statement should look something like this:

if dictionary[key_name][-1] == 0:
    # todo

Output:

>>> dict = {'a':[3,0], 'b':[5,0]}
>>> dict['a'][-1]
0
>>> print(dict['a'][-1] == 0)
True

You can iterate over the dictionary by using the items operation to return pairs of key/values and handle them as you wish. One example is listed below.

for k, v in d.items():
    if v[-1] == 0:
        print('{} -> {}'.format(k, v))

a -> [3, 0]
b -> [5, 0]

The list comprehension

[value[-1] == 0 for _,value in dictionary.items()]

returns a list of True and False values for each of the last items in the dict values. For your test dictionary it returns

[True, True]

Next, you can use all on the list to test if they indeed are all True :

all([value[-1] == 0 for _,value in dictionary.items()])

which returns a single boolean True or False . (And here it'd return True of course.)

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