Home > Software design >  How to select key value pairs elements from a list in Python?
How to select key value pairs elements from a list in Python?

Time:07-07

I'm trying get the values from the below list by calling each of the keys :

l=["'person': 'Male'", "'name': 'James Smith'", "'dob': 'Jul 20 1955'", "'car': 'Ford'"]

desired output:

print(l['person'])

Male

CodePudding user response:

You probably want this to be a dictionary rather than a list.

l = dict([x.replace("'", '').split(': ') for x in l])
print(l['person'])

...

Male

CodePudding user response:

Maybe you wanna use a dictionary structure intead of a list.

If you define the dictionary

my_dict = {"person": "Male", "Name": "james Smith"}

then you can use the keys to index the dictionary

If you run

print(my_dict('person'))

the output will be

Male

CodePudding user response:

If the input is fixed and you want to convert it to dict, this might help.

def convertToDict(arr):
  obj_map = {}
  for obj in arr:
    k, v = obj.split(':')
    obj_map[k.strip(" '")]=v.strip(" '")
  return obj_map

l=convertToDict(l)

print(l['person']) # Man

CodePudding user response:

If you have this list of strings, you could join them with ',' and add curly braces to the end to form a single string, then eval it into a dict.

from ast import literal_eval

d = literal_eval(f"{{{','.join(l)}}}")

print(d['person'])
  • Related