【问题标题】:Printing list indexes from nested dictionaries containing lists从包含列表的嵌套字典中打印列表索引
【发布时间】: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 对象,到其他列表对象,但是,您正在尝试连接 liststr 对象,这将失败。您需要检查一下您使用的是列表还是 str。理想情况下,您可以将任何给您这种混乱输出的东西修复为常规的东西(例如,它们都应该是列表)

标签: python python-3.x list dictionary indexing


【解决方案1】:

在连接到字符串之前,您必须加入列表才能将它们转换为字符串。这可以使用join():

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(f'Animal type: {animal_type}')
    for key, value in animal_info.items():
        if isinstance(value, list):
            print(f"{key}: {', '.join(value)}")
        else:
            print(f'{key}: {value}')

【讨论】:

    【解决方案2】:

    使用连接方法(字符串):

    if isinstance(animal_info[key], list):
        print(key + ':' + ','.join(animal_info[key]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 2018-10-13
      • 1970-01-01
      • 2019-03-29
      • 2020-11-20
      相关资源
      最近更新 更多