简体   繁体   English

如何在python中迭代字典对象

[英]How to iterate dictionary object in python

Can you please guide, how I iterate dictionary in python.你能指导一下,我如何在 python 中迭代字典。

How I get it one by one like key: value key: value My Code:我是如何一一获取的,比如key: value key: value我的代码:

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.取一个变量,比如output ,现在迭代键值对并连接到字符串。 Then return the string.然后返回字符串。

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

return output

Use .items()使用.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?我有一个问题,为什么在推荐的输出中需要单引号?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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