我读了很多教程,但是找不到如何在string.format中像这样迭代dict:
dict = {'this':'I','is':'am','title':'done'}
print(f'the key is {k for k,v in dict}')
print(f'the val is {v for k,v in dict}')我想得到这样的结果:
the key is this is title
the val is I am done这样我就可以打印可变长度的字典了。
dict = {'this':'I','is':'am','title':'done'}
print(f'the key is {k for k,v in dict}')
print(f'the val is {v for k,v in dict}')然后我就出错了。
发布于 2022-09-09 10:31:31
目前,您的输出是:
the key is <generator object <genexpr> at 0x7fbaca5443c0>
the val is <generator object <genexpr> at 0x7fbaca5443c0>这是因为k for k,v in dict是一个生成器表达式。不要把它和集合理解混淆起来,那些花括号是f字串的.
当然,k for k,v in dict是有问题的。当您遍历字典本身时,它会给出键。因此,对于第一次迭代,"this"回来了。您不能将"this"解压缩为两个变量。k, v = "this"。
你可以用这个:
d = {"this": "I", "is": "am", "title": "done"}
print(f'the key is {" ".join(d.keys())}')
print(f'the val is {" ".join(d.values())}')产出:
the key is this is title
the val is I am done此join之所以有效,是因为键和值是字典中的字符串。如果它们不是,您应该将它们转换为:
print(f'the key is {" ".join(map(str, d.values()))}')对于第一个版本,您也可以使用print(f'the key is {" ".join(d)}')作为默认情况下,字典将在迭代中给出键。
发布于 2022-09-09 10:40:33
我会这样做的,如果你不介意在最后有一个空间,我不是专家。
mydict = {"this": "I", "is": "am", "title": "done"}
def get_str(dict):
str_a = ""
str_b = ""
for k in dict:
str_a += f"{k} "
str_b += f"{dict[k]} "
print(str_a)
print(str_b)
get_str(mydict)产出:
this is title
I am done 发布于 2022-09-09 10:51:04
密钥的print("The keys are", ' '.join(k for k in dict))
值的print("The keys are", ' '.join(v for k, v in dict.items()))
https://stackoverflow.com/questions/73660746
复制相似问题