Home > Back-end >  How to extract the the key and values from list of dictionary?
How to extract the the key and values from list of dictionary?

Time:09-17

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'}]

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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

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

CodePudding user response:

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

CodePudding user response:

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

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