python - 打印字典列表中的单独元素

标签 python list dictionary printf element

我在尝试打印字典列表中的每个元素以及字典中的其他项目时遇到问题。

#dictionaries
bill = {
    "name": "Bill",
    "job": "Policeman",
    "hobbies": ["rugby","music","mischief"],
}
jill = {
    "name": "Jill",
    "job": "Lawyer",
    "hobbies": ["driving","clubbing","basketball"],
}
will = {
    "name": "Will",
    "job": "Builder",
    "hobbies": ["football","cooking","beatboxing"],
}

#list of citizens
citizens = [bill,jill,will]

#print keys with their values for each citizen
def citizen_info(citizens):
    for citizen in citizens:
        for item in citizen:
            print ("%s: " + str(citizen[item])) % (item)
        print ""

#Calling citizen_info
citizen_info(citizens)

如您所见,我试图打印每个字典中的所有项目,但是当我尝试打印列表中的单独元素时,它看起来像这样。

job: Policeman

name: Bill

hobbies: ['rugby', 'music', 'mischief']

job: Lawyer

name: Jill

hobbies: ['driving', 'clubbing', 'basketball']

job: Builder

name: Will

hobbies: ['football', 'cooking', 'beatboxing'] 

当我真正喜欢看起来像这样的时候:

hobbies: rugby music mischief

用谷歌搜索这个问题并在这个网站上搜索,我可以找到解决这个问题的解决方案,但如果字典中有另一个不是列表的项目,我就无法找到解决方案。

最佳答案

def citizen_info(citizens):
    for citizen in citizens:
        for item in citizen:
            if type(citizen[item]) is list :
                print ("%s: " + " ".join(citizen[item])) % (item)
            else :
                print ("%s: " + str(citizen[item])) % (item)
        print ""

def citizen_info2(citizens):
    for citizen in citizens:
        for item in citizen:
            if item == "hobbies" :
                print ("%s: " + " ".join(citizen[item])) % (item)
            else :
                print ("%s: " + str(citizen[item])) % (item)
        print ""

如果你有一个列表 a = ['1', '2', '3'] 并且想连接里面的字符串:

" ".join(a)
", ".join(a)

关于python - 打印字典列表中的单独元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31359553/

相关文章:

list - F# 中反转列表的列表

Python 查询最旧日期列表

python - 检索值 'outside' 跨度类 Selenium

c++ - 从 unordered_set 中删除列表元素

python - 对于不在 pypi 中的包,我应该在 pip 需求文件中放入什么

list - LISP:反转点列表

c++ - 如何对 map 使用 copy_if

algorithm - 将STL映射转换为基于数值的键排序列表的好算法

python - CountVectorizer 矩阵随新的分类测试数据变化?

python - python 中超过 50k 个条目的哈希函数和表实现