简体   繁体   中英

How to iterate dictionary object in python

Can you please guide, how I iterate dictionary in python.

How I get it one by one like key: value key: value My Code:

def dist(dict):
    # z = None
    for i in dict:

        print(dict[i])
        z = i+": " + dict[i]
        # print(z)
        # return z

if __name__ == '__main__':
    k = dist({'B_weeks': '40.0 week, 6.0 day, 20.0 hour, 30.0 minute', 'S_weeks': '2.0 week, 3.0 day, 19.0 hour, 59.0 minute'})
    print(k)

Recommended output:

   'B_weeks': '40.0 week, 6.0 day, 20.0 hour, 30.0 minute'
   'S_weeks': '2.0 week, 3.0 day, 19.0 hour, 59.0 minute'

Ho I return this recommended output in one variable from the given function. because i want to use it in another function.

Take a variable, say output and now iterate over the key value pairs and concatenate to the string. Then return the string.

output = ""
for k, v in dict.items():
    output += "{}: {} ".format(k,v)

return output

Use .items()

def dist(k):
    items = k.items()
    for key, value in items:
        print('"{}": "{}"'.format(key, value))
    return items


if __name__ == '__main__':
    k = dist({'B_weeks': '40.0 week, 6.0 day, 20.0 hour, 30.0 minute', 'S_weeks': '2.0 week, 3.0 day, 19.0 hour, 59.0 minute'})
    print(k)
def dict_comprehension(dictionary):
    out=''
    for key,val in dictionary:
        out+="{}:{}".format(key,val)
    return out

You can try the code below.

Code example:

def dist(dictionary):
    out=''
    for key,val in dictionary.items():
        out+="'{}':'{}'\n".format(key,val)
    return out


if __name__ == '__main__':
    k = dist({'B_weeks': '40.0 week, 6.0 day, 20.0 hour, 30.0 minute', 'S_weeks': '2.0 week, 3.0 day, 19.0 hour, 59.0 minute'})
    print(k)

I have a question, why need the single quote in your recommended output?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM