【问题标题】:Dictionary from Automate the boring stuff with Python字典来自用 Python 自动化无聊的东西
【发布时间】:2016-08-26 12:25:08
【问题描述】:

这个程序来自“用python自动化无聊的东西”。我不明白,是什么告诉程序将“name”作为Key,将“bday”作为Value

birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}

   while True:
       print('Enter a name: (blank to quit)')
       name = input()
       if name == '':
           break

    if name in birthdays:
         print(birthdays[name] + ' is the birthday of ' + name)
       else:
           print('I do not have birthday information for ' + name)
           print('What is their birthday?')
           bday = input()
           birthdays[name] = bday
           print('Birthday database updated.')

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    我们可以直接在字典中添加键、值

    供参考:

    d = {}
    print(d)
    d['Name']='1st April';
    print(d)
    

    输出:

    {}
    {'Name': '1st April'}
    

    这里,“名称”是,“4 月 1 日”是

    Python 从括号[] 内识别键和分配的值,如 d[key] = value

    要在字典中查看详细信息,请参阅:Python Dictionary

    【讨论】:

      【解决方案2】:

      您可以阅读 dict 文档:Python dict

      a_dictionnary[xxx] = yyy行中

      xxx 被命名为 keyyyy 被命名为 value

      【讨论】:

        【解决方案3】:

        第 9 行 - if name in birthdays:

        当使用in 关键字对列表进行检查而不向字典添加任何方法时,它会自动检查其键。

        例如,如果birthdays 中的namebirthdays.keys() 中的条目相同,则将bday 设置为用户输入。

        当它像birthdays[name]=bday一样使用时,就像在字典birthdays中添加一个键值对。

        【讨论】:

          猜你喜欢
          • 2020-05-14
          • 1970-01-01
          • 1970-01-01
          • 2020-08-30
          • 1970-01-01
          • 1970-01-01
          • 2018-09-22
          • 2019-10-09
          • 2021-06-07
          相关资源
          最近更新 更多