[英]How to append space at the end of Key and Values in the list of dictionary in python
我想在字典列表中的每个键和值的末尾添加空格。 我知道这听起来很奇怪,但是我有一个要求,需要此类词典列表。 有什么建议么!
例:
# Original List of dictionary
my_list = [{'Table': 'A', 'Column': 'C1', 'DataType': 'int'},
{'Table': 'A', 'Column': 'C2', 'DataType': 'varchar'},
{'Table': 'B', 'Column': 'C3', 'DataType': 'int'}
]
# Have another list of dictionary which specifies the space needs to add at the end of each key and value pair.
position_list = [{'Table': 10}, {'Column': 15}, {'DataType': 10}]
因此,在这里我需要在键的末尾及其值后附加10个空格。
# Expected out put (Spaces may not be exact as shown below but expecting something like.)
list = [{'Table ': 'A ', 'Column ': 'C1 ', 'DataType ': 'int '},
{'Table ': 'A ', 'Column ': 'C2 ', 'DataType ': 'varchar '},
{'Table ': 'B ', 'Column ': 'C3 ', 'DataType ': 'int '}
]
我的字典列表也总是变化,因此my_list和position_list每次都会改变,所以我无法对指定的键和空间进行硬编码。
您可以简单地做到这一点:
from collections import defaultdict
my_list = [{'Table': 'A', 'Column': 'C1', 'DataType': 'int'},
{'Table': 'A', 'Column': 'C2', 'DataType': 'varchar'},
{'Table': 'B', 'Column': 'C3', 'DataType': 'int'}]
position_list = [{'Table': 10}, {'Column': 15}, {'DataType': 10}]
positions = defaultdict(lambda : 10)
for d in position_list:
positions.update(d)
print [{k + ' ' * positions[k] : v + ' ' * positions[v] for k,v in d.items()} for d in my_list]
输出:
[{'DataType ': 'int ', 'Table ': 'A ', 'Column ': 'C1 '}, {'DataType ': 'varchar ', 'Table ': 'A ', 'Column ': 'C2 '}, {'DataType ': 'int ', 'Table ': 'B ', 'Column ': 'C3 '}]
编辑:
如果您希望键和值具有相同的间距,只需使用此positions[k]
( positions[k]
而不是postions[v]
)。
print [{k + ' ' * positions[k] : v + ' ' * positions[k] for k,v in d.items()} for d in my_list]
我不知道你为什么需要这个。 违反PEP 0008
无论如何,执行此操作的一种方法是使用str.format()
方法来格式化键/值对。 但是首先,您需要将“ position_list”转换为常规dict
。 然后遍历dict
列表并格式化项目。
>>> my_list = [{'Column': 'C1', 'DataType': 'int', 'Table': 'A'},
... {'Column': 'C2', 'DataType': 'varchar', 'Table': 'A'},
... {'Column': 'C3', 'DataType': 'int', 'Table': 'B'}]
>>> position_list = [{'Table': 10}, {'Column': 15}, {'DataType': 10}]
>>> d = {k:v for item in position_list for k, v in item.items()}
>>> res = []
>>> for element in my_list:
... item = {}
... for key, value in element.items():
... width = len(key) + d[key]
... item["{:<{width}}".format(key, width=width)] = "{:<{width}}".format(value, width=width)
... res.append(item)
...
>>> import pprint # Just to pretty print res nothing special.
>>> pprint.pprint(res)
[{'Column ': 'C1 ',
'DataType ': 'int ',
'Table ': 'A '},
{'Column ': 'C2 ',
'DataType ': 'varchar ',
'Table ': 'A '},
{'Column ': 'C3 ',
'DataType ': 'int ',
'Table ': 'B '}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.