Reputation: 57
I've got a list of tuples which look like this.
people = [('John', 36, 'M'), ('Rachel', 24, 'F'), ('Deardrie', 78, 'F'), ('Ahmed', 17, 'M'), ('Sienna', 14, 'F')]
I'm trying to create a function. which has 2 parametres function(people, name) The function should return a dictionary with two keys, "age" and "gender", with the values being those from the tuple which contains the name passed as the second argument to the function. If the name isn't found in the list of tuples, return "None."
I'm struggling to create a function as i can't seem to find any information on how to approach a 3 element list of tuples.
any tips on how to approach this?
Upvotes: 0
Views: 1601
Reputation: 1
Here is a function that returns list of dictionaries. If there are several tuples with the same name then the function returns all of them inside the list as a dictionaries. If there is not any tuple with the specific name then None
is returned.
def my_f(people, name):
result = []
for each in people:
if each[0] == name:
result.append({'age': each[1], 'gender': each[2]})
if len(result) == 0:
return None
return result
Upvotes: 0
Reputation: 1268
people = [('John', 36, 'M'), ('Rachel', 24, 'F'), ('Deardrie', 78, 'F'), ('Ahmed', 17, 'M'), ('Sienna', 14, 'F')]
def my_func(people, name:str):
b = {}
for person in people:
if person[0] == name:
b["Age"] = person[1]
b["Gender"] = person[2]
if len(b)>0:
return b
else:
return None
c = my_func(people, 'Rachel')
print(c)
d = my_func(people, 'Diana')
print("\n" + str(d))
my output:
{'Age': 24, 'Gender': 'F'}
None
Upvotes: 0
Reputation: 1281
Something like this?
people1 = [('John', 36, 'M'), ('Rachel', 24, 'F'), ('Deardrie', 78, 'F'), ('Ahmed', 17, 'M'), ('Sienna', 14, 'F')]
def xyz(people, name):
found={}
for _name,_age,_gender in people:
if _name==name:
found["Age"]=_age
found["Gender"]=_gender
return found
return None
print(xyz(people1,"John"))
print(xyz(people1,"John1"))
{'Age': 36, 'Gender': 'M'}
None
Upvotes: 2