简体   繁体   English

如何从字典中打印带有可变数量的键+值的格式化字符串

[英]How to print a formatted string with variable amount of key + values from a dictionary

Is it possible to print variable amount of key+values from a dictionary with str.format()? 是否可以使用str.format()从字典中打印可变数量的键+值? It would be nice if that would work in python2. 如果可以在python2中使用,那就太好了。

let's say I have a dictionary with some amount of keys+values, and I have to print keys+values of those keys which are stored in a list/tuple. 假设我有一本包含一些键+值的字典,我必须打印存储在列表/元组中的那些键+值。

dict1 = { 'k1':'v1', 'k2':'v2', 'k3':'v3'}
to_print = ('k1', 'k2')
string = ''
for i in dict1:
    if i in to_print:
        string += "{" + i + "} " +  ', '

string = string.format(**dict1)
print(string[:-2])

The above code gives 上面的代码给出

v1 , v2 

while I would like it to be formatted like this: 虽然我希望将其格式化为:

[k1] v1 , [k2] v2

UPD: UPD:

having challenges with that solution if a dictionaries are inside a list and i need to print key/values from one dictionary in one row, example: 如果字典在列表中并且我需要从一行中的一本字典中打印键/值,则该解决方案会遇到挑战,例如:

list1  = [ { 'k1':'v1', 'k2':'v2', 'k3':'v3'} , { 'k1':'v4', 'k2':'v5', 'k3':'v6'} ] 
to_print = ('k1', 'k2')
for i in list1:
    for k,v in i.items():
        if k in to_print:
            elements = []
            elements.append(f"[{k}]: {v}")
            print(", ".join(elements))
[k1]: v1
[k2]: v2
[k1]: v4
[k2]: v5

while I need something like this: 而我需要这样的东西:

[k1]: v1 , [k2]: v2
[k1]: v4 , [k2]: v5

Previously, I addressed that with the grouped function from the SO: 以前,我使用SO中的分组功能解决了这个问题:

def grouped(iterable, n):
    "s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), (s2n,s2n+1,s2n+2,...s3n-1), ..."
    return zip(*[iter(iterable)] * n)

any idea to make that better? 有什么想法可以使它变得更好吗?

ok, figured that out: 好,知道了:

elements = []
for i in list1:
    elements = []
    for k,v in i.items():
        if k in to_print:
            elements.append(f"[{k}]: {v}")
    print(", ".join(elements))```
dict1 = { 'k1':'v1', 'k2':'v2', 'k3':'v3'}
to_print = ('k1', 'k2')

elements = []
for key, val in dict1.items():
    if key in to_print:
        elements.append(f"[{key}]: {val}")

print(", ".join(elements))

Or could be done even shorter by using list comprehension: 或者可以通过使用列表理解来做得更短:

print(", ".join([f"[{key}]: {val}" for key, val in dict1.items() if key in to_print]))

will yield: 将产生:

[k1]: v1, [k2]: v2, [k3]: v3

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

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