如何使用python中的字典从包含多个值的键访问单个值

2024-10-01 15:29:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python还很陌生,并试图在词典中提问,但我被困在这个问题上

Q.字典编码 描述 编写代码,从字典形式给出的员工输入中获取员工id为-104的员工职业,其中键表示雇员id,值表示姓名、年龄和职业(顺序相同)

样本输入:

Employee_data = { 101:['Shiva', 24, 'Content Strategist'] ,102:['Udit',25,'Content Strategist'], 103:['Sonam', 28,'Sr Manager'], 104:['Ansari',29,'Product Lead' ],105:['Huzefa',32,'Project Manager' ]}

样本输出:

'Product Lead'

Tags: 代码id编码字典员工managercontentproduct
3条回答

请尝试以下代码:

import ast,sys
input_str = sys.stdin.read()
input_dict = ast.literal_eval(input_str)

Employee_list = list( input_dict[104])

profession = Employee_list[2]


print(profession)

然而,在我的空闲环境中,它按预期工作,而在上面的代码中实现相同的功能时,我没有得到正确的输出

我的代码:

input_str = '101'
input_dict = {101:['Shiva', 24, 'Content Strategist'] ,102:['Udit',25,'Content Strategist'], 103:['Sonam', 28,'Sr Manager']}
profession=input_dict[int(input_str)][2]
print(profession)

但在上面的门户中,我无法给出profession=input_dict[int(input_string)][2]

def getProfession(id):
    return Employee_data[id][2] # second element is the profession

print(getProfession(104)) # Returns "Product Lead"

这里是我创建的一个函数,当在其参数中使用id调用它时,它返回值。Python(在我看来)是一种很好的编程语言,可以从列表中进行索引,或者只需包含一个[index]即可返回所需的元素

相关问题 更多 >

    热门问题