📜  Python – 打印列表值字典

📅  最后修改于: 2022-05-13 01:55:47.572000             🧑  作者: Mango

Python – 打印列表值字典

在本文中,我们将打印一个列表值字典。列表值字典意味着字典包含作为字典列表的值

例子:

所以我们必须根据键来获取列表中存在的字典。我们可以通过使用 dict.items() 来获得它。

语法

d.items()

我们可以使用 for 循环遍历字典

for key,values in data.items():
     for i in values:
          print(key," : ",i)

示例 1:用于创建字典的Python代码,其中学生姓名作为键,值作为主题详细信息

Python3
# create a dictionary
# with student names as key
# values as subject details
data = {'manoja': [{'subject1': "java", 'marks': 98}, 
                   {'subject2': "PHP", 'marks': 89}],
        'manoj': [{'subject1': "java", 'marks': 78}, 
                  {'subject2': "PHP", 'marks': 79}]}
  
# get the list of data
# using items() method
for key, values in data.items():
    for i in values:
        print(key, " : ", i)


Python3
# create a dictionary
# with student names as key
# values as subject details
data = {'manoja': [{'subject1': "java", 'marks': 98}, 
                   {'subject2': "PHP", 'marks': 89}],
        'manoj': [{'subject1': "java", 'marks': 78},
                  {'subject2': "PHP", 'marks': 79}],
        'ramya': [{'subject1': "html", 'marks': 78}]}
  
# get the list of data
# using items() method
for key, values in data.items():
    for i in values:
        print(key, " : ", i)


输出

manoja  :  {'subject1': 'java', 'marks': 98}
manoja  :  {'subject2': 'PHP', 'marks': 89}
manoj  :  {'subject1': 'java', 'marks': 78}
manoj  :  {'subject2': 'PHP', 'marks': 79}

示例 2

Python3

# create a dictionary
# with student names as key
# values as subject details
data = {'manoja': [{'subject1': "java", 'marks': 98}, 
                   {'subject2': "PHP", 'marks': 89}],
        'manoj': [{'subject1': "java", 'marks': 78},
                  {'subject2': "PHP", 'marks': 79}],
        'ramya': [{'subject1': "html", 'marks': 78}]}
  
# get the list of data
# using items() method
for key, values in data.items():
    for i in values:
        print(key, " : ", i)

输出

manoja  :  {'subject1': 'java', 'marks': 98}
manoja  :  {'subject2': 'PHP', 'marks': 89}
manoj  :  {'subject1': 'java', 'marks': 78}
manoj  :  {'subject2': 'PHP', 'marks': 79}
ramya  :  {'subject1': 'html', 'marks': 78}