my_dict = {1: ['Serena', 'Williams', 38],2: ['Bradley', 'Cooper', 45],3: ['Wendy', 'Williams', 56],4: ['Bill', 'Gates', 72], 5: ['Normani', 'Kordei', 24]}
I have that dictionary with a list as values and I'm trying to access say the age (index 2 in the list) of key 3 when found. I tried this code
def record(num):
my_dict = {1: ['Serena', 'Williams', 38],2: ['Bradley', 'Cooper', 45],3: ['Wendy', 'Williams', 56],
4: ['Bill', 'Gates', 72], 5:['Normani', 'Kordei', 24]}
for k, v in my_dict.items():
fname = v[0]
lname = v[1]
age = v[2]
if my_dict.get(num) is None:
print('Not found')
else:
print(num, age, 'Found')
record(3) # Call function
I want something like if I call the function with record(3) I just get the age corresponding to that key like this:
3 56 Found
Currently I get:
3 38 Found
3 45 Found
3 56 Found
3 72 Found
3 24 Found
You don't need to use a loop, you can just index directly into the dictionary.
def record(num):
my_dict = {1: ['Serena', 'Williams', 38],2: ['Bradley', 'Cooper', 45],3: ['Wendy', 'Williams', 56],
4: ['Bill', 'Gates', 72], 5:['Normani', 'Kordei', 24]}
if num in my_dict:
print(num, my_dict[num][2], "Found")
else:
print("Not found")
or use try-except to handle the "not found" case (which some may argue is more "Pythonic"):
def record(num):
my_dict = {1: ['Serena', 'Williams', 38],2: ['Bradley', 'Cooper', 45],3: ['Wendy', 'Williams', 56],
4: ['Bill', 'Gates', 72], 5:['Normani', 'Kordei', 24]}
try:
print(num, my_dict[num][2], "Found")
except KeyError:
print("Not found")
As noted in SuperStormer's answer , you should be directly accessing the record for num
by invoking the key on the directory. However using the iteration process you do, the correct item to check is whether k
matches the desired key num
.
Note this approach is not recommended - this is just a clean-up of your method:
my_dict = {1: ['Serena', 'Williams', 38], 2: ['Bradley', 'Cooper', 45],
3: ['Wendy', 'Williams', 56], 4: ['Bill', 'Gates', 72],
5:['Normani', 'Kordei', 24]}
def record(num):
for k, v in my_dict.items():
fname, lname, age = v
if k == num:
print(num, age, 'Found')
return
print (num, "Not found")
for a in range(7): # Call function repeatedly to check cases
record(a)
The output from the seven calls to record
above is:
0 Not found
1 38 Found
2 45 Found
3 56 Found
4 72 Found
5 24 Found
6 Not found
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.