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

时间:2015-07-11 16:54:41

标签: python list dictionary printf elements

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

#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

通过Google搜索此问题并在此网站上搜索,我可以找到解决此问题的解决方案,但如果字典中的其他项目不是列表,则无效。

5 个答案:

答案 0 :(得分:2)

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)

答案 1 :(得分:1)

如果值为list,则可以使用三元条件生成由空格连接的字符串,否则使用简单字符串。

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

答案 2 :(得分:1)

def citizen_info(citizens):
    for citizen in citizens:
        for item in citizen:
            if item != 'hobbies':
                print ('{}: {}'.format(item, citizen[item])  # new style string formatting, much easier to read imo
            else:
                print ('{}: {}'.format(item, ' '.join(citizen[item]))
        print ""

使用新样式字符串格式并仅以不同方式处理hobbies键。

答案 3 :(得分:0)

分别循环浏览爱好键:

#print keys with their values for each citizen
def citizen_info(citizens):
    for citizen in citizens:
        for item in citizen:
            if item != "hobbies":
                print(("%s: " + str(citizen[item])) % (item))
            else:
                print("hobbies", end="")
                for hobby in citizen[item]:
                    print(hobby, end="")
                print("")
    print("")

答案 4 :(得分:0)

看看这是否适合你:

def citizen_info(citizens):
  for citizen in citizens:  # loop through the citizens
    for key, value in citizen.items():  # get keys and values
      if type(value) is list:  # test if the value is a list
        value = " ".join(value)  # join the list into a string
      print("{}: {}".format(key, value))  # print however you want