简体   繁体   中英

How to get a specific value from a python dictionary

I have a Python dictionary and I want to extract one specific value for a column and use it in my code . I am unable to get that value .

d = {"col": [
                        {"Name":"cl1",
                         "length":12,
                         "columnType":"xes",
                         "type":"string"
                        },
                        {"Name":"cl2",
                         "length":13,
                         "columnType":"xyx",
                         "type":"string"
                        },
                        {"Name":"cl3",
                         "length":14,
                         "columnType":"xyz",
                         "type":"string"
                        }

                    ]
          }

How to get the value stored for "Name" in the dictionary 'd'

There are multiple values for the key "Name" in d , however, you can get a listing of all names like so:

names = [i["Name"] for i in d['col']]

Output:

['cl1', 'cl2', 'cl3']

As noted, another way may be to iterate the dictionary values:

for i in range(len(d['col'])):
    print d['col'][i]['Name']

output:

cl1
cl2
cl3

Here i is the index of each value in the d['col'] list.

another way to do this is to:

lst = d["col"]
for dic in lst: 
  print(dic["Name"])

The first line takes the dictionary and gives the list value back in the variable 'lst'. Then the next line iterates through the list to each dictionary inside the list. The third line gets the value from the dictionary key = 'Name'. If you want another value just change the key.

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