python - 可以将单个单词'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])
我将不胜感激任何建议甚至替代方法来实现这一目标。非常感谢。
解决方案
我想说在您的代码中只包含另一本字典可能是最简单的。例如:
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'])
推荐阅读
- c - main() 在运行时异常返回什么?
- java - 如何修复指定为非空的参数是Android中的空错误
- sdl - 如何安装 SDL lib 并将其交叉编译到嵌入式 linux (hisiv300)
- perforce - 如何在 Perforce 流中包含一个被忽略的文件夹结构中的特定文件?
- c# - 如果在设计期间启用 = false,则灰色 UserControl 输出
- java - 保持最大精度水平
- avfoundation - AVAudioRecorder:加快录音的播放速度?(不能用 AVAudioPlayer 快速播放)
- android - 未收到有关 Moto E4 plus 的通知
- python-3.x - 如何修复从.csv加载的经纬度并正确上路?
- python - 为什么学习率不变?