【发布时间】:2019-02-06 18:41:06
【问题描述】:
我正在尝试从由嵌套字典和列表组成的字典进行打印。不幸的是,我无法使用length > 1 从列表中打印项目。这是我的代码:
animals = {
'cats': {
'name': 'moose',
'color': 'black & white',
'alias':'Moosalini'
},
'dogs': {
'name': ['scout', 'sulley'],
'color': 'white & orange',
'alias': ['skump', 'skulley']
}
}
for animal_type, animal_info in animals.items():
print('Animal type: ', animal_type)
for key in animal_info:
print(key + ': ' + animal_info[key])
输出正是我想要的,直到它到达与 'name' 关联的列表,在键 'dogs' 下。我的代码不会连接列表,因为它不是字符串。我认为可以像字符串一样连接列表?
Animal type: cats
name: moose
color: black & white
alias: Moosalini
Animal type: dogs
Traceback (most recent call last):
File "/Users/Jaron/Documents/nested dictionary.py", line 14, in <module>
print ( key + ': ' + animal_info[key])
TypeError: can only concatenate str (not "list") to str
我尝试将 str() 函数放在 animal_info[key] 前面,它允许连接,但包括这样的列表括号。
Animal type: dogs
name: ['scout', 'sulley']
color: white & orange
alias: ['skump', 'skulley']
我希望输出如下所示:
Animal type: cats
name: moose
color: black & white
alias: Moosalini
Animal type: dogs
name: scout, sulley
color: black & white
alias: skump, skulley
如何在嵌套字典中的字典中的列表中指定项目索引,以便字符串连接起作用?另外,有没有一种方法可以使列表的连接可以与程序一起使用,而无需保留列表括号 []?任何帮助表示赞赏!
【问题讨论】:
-
请注意,您可以更轻松地循环
for key, value in animals.items():无论如何,一个可以连接list对象,到其他列表对象,但是,您正在尝试连接list和str对象,这将失败。您需要检查一下您使用的是列表还是 str。理想情况下,您可以将任何给您这种混乱输出的东西修复为常规的东西(例如,它们都应该是列表)
标签: python python-3.x list dictionary indexing