我想打印字典字符串的键和值。例如,a = [{'1': '0'}, {'9': '2'}, {'4': '3'}, {'3': '5'}, {'0': '7'}, [], [], [], []]我尝试了这个:for x in a: for y in x.values(): print(y)不工作for x in a: for y in x.itervalues(): print(y)不工作for x in a: for y in x.items(): print(y)不工作反正要这样打印吗?:1 09 24 33 50 7或者keys = 1,9,4,3,0values = 0,2,3,5,7
2 回答
饮歌长啸
TA贡献1951条经验 获得超3个赞
一种可能的解决方案是使用列表理解来过滤掉非字典,然后将字典转换为键值元组,并使用以下键将键和值分开zip
:
k,v = zip(*[list(x.items())[0] for x in a if isinstance(x, dict)]) print(k,v) #('1', '9', '4', '3', '0') ('0', '2', '3', '5', '7')
慕勒3428872
TA贡献1848条经验 获得超6个赞
而且,如果您希望并排键/值对输出,则可以执行以下操作(如果任何词典包含多个键/值对,则需要更改代码):
for x in a:
if isinstance(x, dict):
# "if isinstance" is here just to ignore the lists in your list,
# you may want to do something else with those
print(x.keys(), x.values())
# (['1'], ['0'])
# (['9'], ['2'])
# (['4'], ['3'])
# (['3'], ['5'])
# (['0'], ['7'])
如果您需要处理字典项中的多个键/值对并仅打印值(减去格式),则应如下所示:
for x in a:
if isinstance(x, dict):
tups = x.items()
for tup in tups:
print('{} {}'.format(tup[0], tup[1]))
# 1 0
# 9 2
# 4 3
# 3 5
# 0 7
添加回答
举报
0/150
提交
取消