【问题标题】:Pulling 1 item from a list in a dictionary (Python)从字典中的列表中提取 1 个项目(Python)
【发布时间】:2014-01-09 14:44:35
【问题描述】:

所以我有一个字典,其中的键包含项目列表。

some_dict= {
    'thing_one' : ['Test', '1', 'one', "uno"],
    'thing_two' : ['Scissors', 'Dos', 'two'],
          }

现在假设我要打印“测试”

print (some_dict['thing_one'])

返回

'Test', '1', 'one', "uno"

所以如果我尝试拉出第一个项目...

print (some_dict['thing_one'[0]])

我明白了……

KeyError: 't'

【问题讨论】:

  • 旁白:print (some_dict['thing_one']) 应该打印['Test', '1', 'one', 'uno'](带括号),所以我怀疑它是否如您所说。从技术上讲,它不 return 任何东西(print 不是 Python 2 中的函数)。它输出列表表示。在 Python 3 中,它将返回 None。

标签: python list python-2.7 dictionary


【解决方案1】:

移动括号:

print (some_dict['thing_one'][0])

这会将[0] 索引应用于some_dict['thing_one'] 表达式的结果。

您正在索引字符串 'thing_one',而该字符串的第一个字符是 't':

>>> 'thing_one'[0]
't'

并且't' 不是您的some_dict 字典中的键。

【讨论】:

    猜你喜欢
    • 2022-11-21
    • 2021-12-05
    • 1970-01-01
    • 2021-07-11
    • 2017-12-15
    • 2020-09-04
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多