首页 > 解决方案 > 可以将单个单词'string'转换为同名字典吗

问题描述

我的程序以一个名字列表开始。例如:['Bob','John','Mike']' 然后将这个列表打乱成随机顺序。例如:['Mike','Bob','John'] 然后从列表中获取一个名称。例如:['Mike'] 离开 ['Bob','John']

然后,我想将此名称与同名字典相关联。例如:'Mike' = {'Surname' : 'Jones', 'Age': 55, 'Staff ID': 101}

然后能够调用并打印特定的 Key : Value 所选名称。例如:打印(迈克[年龄])

(我目前的代码和这个例子类似)

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]) 

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

标签: pythonlistdictionary

解决方案


我想说在您的代码中只包含另一本字典可能是最简单的。例如:

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

推荐阅读