This question already has answers here:
How do I create a variable number of variables?
                                
                                    (14个回答)
                                
                        
                                12个月前关闭。
            
                    
我的程序以名称列表开头。例如:['Bob','John','Mike']'然后,此列表被随机排列。例如:['Mike','Bob','John']然后从列表中取一个名字。例如:['Mike']离开['Bob','John']

然后,我想将此名称与同名字典相关联。例如:“迈克” = {“姓氏”:“琼斯”,“年龄”:55,“工作人员ID”:101}

然后可以调用并打印特定的Key:所选名称的值。例如:print(Mike [Age])

(我目前的代码类似于此示例)

list_of_names = ['Bob','John','Mary','Joan','Mike']
chosen_name = list_of_names.pop(0)
print("person chosen: ", (chosen_name))

# Dictionaries are pre-formatted waiting to be paired with their listed name
'Bob' = {'Surname' : 'Kelly', 'Age': 49, 'Staff ID': 86},
'John' = {'Surname' : 'Hogan', 'Age': 57, 'Staff ID': 22},
'Mike' = {'Surname' : 'Jones', 'Age': 55, 'Staff ID': 101},

# Prints the randomly chosen name and the dictionary associated with it.
print(chosen_name)

# Prints a Value for a particular key of that chosen name
print(chosen_name[Age])


我将不胜感激任何建议或什至替代方法来实现这一目标。非常感谢。

最佳答案

我想说,在您的代码中再添加一个字典可能是最简单的。例如:

list_of_names = ['Bob','John','Mary','Joan','Mike']
chosen_name = list_of_names.pop(0)
print("person chosen: ", (chosen_name))

# Dictionaries are pre-formatted waiting to be paired with their listed name
person_info = {}
person_info['Bob']  = {'Surname' : 'Kelly', 'Age': 49, 'Staff ID': 86}
person_info['John'] = {'Surname' : 'Hogan', 'Age': 57, 'Staff ID': 22}
person_info['Mike'] = {'Surname' : 'Jones', 'Age': 55, 'Staff ID': 101}

# Prints the randomly chosen name and the dictionary associated with it.
print(person_info[chosen_name])

# Prints a Value for a particular key of that chosen name
print(person_info[chosen_name]['Age'])

10-08 02:22