Printing individual items in lists in dictionaries

I am having a problem trying to print every item in a list in a dictionary as well as other dictionary items.

#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)

      

As you can see, I am trying to print all the elements in each dictionary, but when I try to print the individual elements in the lists, it looks like this.

job: Policeman

name: Bill

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

job: Lawyer

name: Jill

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

job: Builder

name: Will

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

      

When I actually go to look like this:

hobbies: rugby music mischief

      

After searching for this problem and searching this site, I can find solutions that solve this problem, but does not work if there is another item in the dictionary that is not a list.

+3


source to share


5 answers


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 ""

      

or

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 ""

      



If you have a list a = ['1', '2', '3'] and want to join the lines inside:

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

      

+2


source


You can simply use a ternary condition that generates a string concatenated with spaces if the value is of type list

and a simple string otherwise.



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 ""

      

+1


source


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 ""

      

Using a new style of string formatting and just treating the key hobbies

differently.

+1


source


Just scroll through the hobby key separately:

#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("")

      

0


source


See if this works for you:

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

      

0


source







All Articles