简体   繁体   中英

How to extract the the key and values from list of dictionary?

How to extract the the key and values from list of dictionary?

Below is my data, i want to extract the key and values from list of dictionary.

data = [{'index': 0,
      'MaterialCode': '67567412',
      'DP_Category': 'HAIR CARE'},
      {'index': 1,
      'MaterialCode': '67567412',
      'DP_Category': 'HAIR CARE'}]

keys = []
for d in data:
    keys += list(d.keys())

values = []
for d in data:
    values += list(d.values())
data = [
    {"index": 0, "MaterialCode": "67567412", "DP_Category": "HAIR CARE"},
    {"index": 1, "MaterialCode": "67567412", "DP_Category": "HAIR CARE"},
]

for idx, elem in enumerate(data):
    for key, value in elem.items():
        print(f"List element: {idx:>2} Key: {key:<20} Value: {value}")

output

List element:  0 Key: index                Value: 0
List element:  0 Key: MaterialCode         Value: 67567412
List element:  0 Key: DP_Category          Value: HAIR CARE
List element:  1 Key: index                Value: 1
List element:  1 Key: MaterialCode         Value: 67567412
List element:  1 Key: DP_Category          Value: HAIR CARE

If you want to display all keys and values then you need two nested for -loops:

  • first to get dictionary from list,
  • second to get keys and values from dictionary.

Somethink like this:

data = [
    {'index': 0, 'MaterialCode': '67567412', 'DP_Category': 'HAIR CARE'},
    {'index': 1, 'MaterialCode': '67567412', 'DP_Category': 'HAIR CARE'}
]

for item in data:
    for key, val in item.items():
        print(f'{key}: {val}')

Result:

index: 0
MaterialCode: 67567412
DP_Category: HAIR CARE
index: 1
MaterialCode: 67567412
DP_Category: HAIR CARE

And if you need something different then you have to describe it in question.

you can just use this method dist.items() to extract all the key and value. For example, supposing the dict that you wanna extract from

for k, v in dict.items():
 print(k,v) #you can get a couple of key and value
data = [{'index': 0,
      'MaterialCode': '67567412',
      'DP_Category': 'HAIR CARE'},
      {'index': 1,
      'MaterialCode': '67567412',
      'DP_Category': 'HAIR CARE'}]

print(data[0]["MaterialCode"])

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