可以将单个单词“字符串”转换为同名词典

时间:2019-03-02 23:33:09

标签: python list dictionary

我的程序以名称列表开头。例如:['Bob','John','Mike']'然后,此列表被随机排列。例如:['Mike','Bob','John']然后从列表中取一个名字。例如:['Mike']离开['Bob','John']

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

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

(我目前的代码与此示例相似)

2>&1

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

1 个答案:

答案 0 :(得分:1)

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

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