在字典中给出部分键时检索值

时间:2015-12-19 08:00:13

标签: python python-3.x dictionary

我在Python中有一个问题,我们输入了员工的名字,员工的姓氏和他/她的电话号码。

如果我们提供名字,姓氏或两者,我们必须创建一个目录,其中应该生成具有公用名的所有员工的编号。

E.g。如果员工姓名为John,则该计划必须打印John PaulMichel John的电话号码。

d = {}
a = int(input('the total number of employees in the company:'))

for i in range(0, a):
    x = input('first name of the employee:')
    y = input('the last name of the employee:')
    z = int(input('the phone number of the employee:'))
    d2 = {x: z, y: z}
    d.update(d2)

b = input('the partial or the full name of the employee you need the phone number of:')
print(d[b])

我可以在我的代码中找到错误(在通用名称的情况下更新字典而不是创建新条目,因此在公共条目的情况下仅显示一个数字(最后一个条目)。)

2 个答案:

答案 0 :(得分:1)

如果您想通过dict获得速度,可以使用两个dicts来执行此任务。第一个字典是从全名到电话号码的映射,第二个字典是从通用名称到全名列表的映射。

>>> phones = {'John Paul': '12345', 'Michael John': '54321'}
>>> names = {'John': ['John Paul', 'Michael John'],
...          'Paul': ['John Paul'],
...          'Michael': ['Michael John']}
>>> def get_phones(common_name):
...     for full_name in names[common_name]:
...         yield full_name, phones[full_name]
...
>>> list(get_phones('John'))
[('John Paul', '12345'), ('Michael John', '54321')]

新重新编码的插入与此类似:

def insert_phone(full_name, phone):
    for common_name in full_name.split():
        if common_name not in names: names[common_name] = []
        names[common_name].append(full_name)
    phones[full_name] = phone

答案 1 :(得分:0)

我稍微重复了一些例子:

d = {}
st = ''
a = int(input('the total number of employees in the company:'))

for i in range(0, a):
    d[i]['firstname'] = input('first name of the employee:')
    d[i]['lastname'] = input('the last name of the employee:')
    d[i]['phone'] = input('the phone number of the employee:')

b = input('the partial or the full name of the employee you need the phone number of:')
for k, v in d.items():
    for k1, v1 in v.items():
        if b in v1:
            st += ' '.join([v['firstname'], v['lastname'], v['phone'], '\n'])
print(st)

>>> d[0] = {'firstname': 'alex', 'lastname': 'brooke', 'phone': '22234'}
>>> d[1] = {'firstname': 'kelvin', 'lastname': 'mario', 'phone': '22333'}
>>> d[2] = {'firstname': 'kelvin', 'lastname': 'santa', 'phone': '233989'}
>>> b = 'kelvin'
>>> print(st)
kelvin mario 22333
kelvin santa 233989