【问题标题】:Retrieving value when partial key is given in dictionary在字典中给出部分键时检索值
【发布时间】:2015-12-19 08:00:13
【问题描述】:

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

我们必须创建一个目录,如果我们给出名字、姓氏或两者都给出,则应该生成所有具有共同姓名的员工的编号。

例如员工的名字为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])

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

【问题讨论】:

  • 数据结构的方式是问题所在,必须遍历每个键才能找到所需的内容,这违背了 dict 的全部要点,您还不如使用列表。您也不能按照建议使用 in ,因为您最终会得到无意义的输出,因为您将匹配任何子字符串

标签: python python-3.x dictionary


【解决方案1】:

只需遍历 dict 键并获取给定输入所在的键的相应值。

print([d[i] for i in d if b in i]) 

例子:

>>> d = {'John paul': 'foo', 'Michael John': 'bar'}

>>> b = 'John'
>>> [d[i] for i in d if b in i]
['bar', 'foo']

>>> b = 'jOhN'
>>> [d[i] for i in d if b.lower() in i.lower()]
['bar', 'foo']

【讨论】:

  • 这将匹配"foo in foobar"
  • [d[i] for i in d if b.lower() in [j.lower() for j in i.split()]]
  • 当您必须编写这样的解决方案时,您可以很确定有些地方出了问题。 i.lower().split() 也可能更有意义
  • @PadraicCunningham 忘记了……[d[i] for i in d if b.lower() in i.lower().split()]
【解决方案2】:

如果你想使用 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')]

新recode的插入类似这样:

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

【讨论】:

    【解决方案3】:

    我稍微修改了示例:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-01
      • 2019-01-28
      • 2018-02-12
      • 2021-10-25
      • 1970-01-01
      • 2019-06-25
      • 2023-02-08
      • 2019-01-23
      相关资源
      最近更新 更多