简体   繁体   中英

access the element in list of dictionary in python

hi every one i have list of dictionary all of the dictionaries like this:

 dict1 = {Label:----,Chapter:----,Section:----,Massage:----}
 dict2 = {Label:----,Chapter:----,Section:----,Massage:----}
 dict3 = {Label:----,Chapter:----,Section:----,Massage:----}
 List = [dict1 , dict2 , dict3]

i want first the all dictionaries of list if the my label is equal with label in dictionary print the massage of that dictionary.

i use this method but it get nothing.

def printMassage(List , mylabel):
    for dicts in List:
        if (Label.value == mylabel):
            print( Massage.value)

please help me!!

How dictionary in python works

value = dictionary[key]  # get the `value` of `key` in `dictionary`.
dictionary[key] = newvalue  # change the content of `key` in `dictionary` to `newvalue`.

Your example

def printMassage(List , mylabel):
    for dict in List:
        if (dict["Label"] == mylabel):
            print(dict["Massage"])
def printMassage(List , mylabel):
    for dicts in List:
        if dicts[Label] == mylabel:
            print(dicts[Massage])

When accessing values in dictionaries, you need to use the key as the lookup:

def printMassage(List , mylabel):
    for d in List:
        if d['Label'] == mylabel:
            print(d['Massage'])

A one-liner:

def printMassage(List , mylabel):
    print([d['Massage'] for d in List if d[Label] == mylabel])

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