首页 > 解决方案 > Python - 努力使用字典以以下格式打印

问题描述

我打印了一些看起来像这样的代码:

print(len(no_of_records))

200
150
2000

我有一个字典列表,例如:

list_names = {
    "Yellow_List": "yellow",
    "Blue_List": "blue",
    "Red_List": "red"
}

我希望能够在字典中打印我的键名,记录数如下:

The yellow list has 200
The blue list has 150
The red list has 2000

我试过这个

for key in list_names:
    print("The", key, "has", len(no_of_records))

但我得到:

The yellow list has 200
The blue list has 200
The red list has 200
The yellow list has 150
The blue list has 150
The red list has 150
The yellow list has 2000
The blue list has 2000
The red list has 2000

标签: pythonpython-3.xlistprinting

解决方案


你可以这样做:

no_records = [200, 150, 2000]
list_names = {
    "Yellow_List": "yellow",
    "Blue_List": "blue",
    "Red_List": "red"
}

for key, x in zip(list_names.values(), no_records):
    print('The', key, 'list has', x)
The yellow list has 200
The blue list has 150
The red list has 2000

推荐阅读