Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing separate elements in lists in dictionaries

I'm having a problem trying a print each element in a list in a dictionary as well as the other items in the dictionary.

#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 items in each dictionary, but when I try to print the separate 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 hobbies to look like this:

hobbies: rugby music mischief

Having Googled this problem and searched through on this site, I can find solutions where this problem is solved, but does not work if there is another item in the dictionary that is not a list.

like image 685
Matthew Avatar asked Dec 30 '25 22:12

Matthew


1 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 strings inside:

" ".join(a)
", ".join(a)
like image 82
Mihai Hangiu Avatar answered Jan 01 '26 12:01

Mihai Hangiu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!