![](/img/trans.png)
[英]How to print all the keys and values together from a nested dictionary in Python?
[英]How to print first 5 keys and values from dictionary in Python for below code?
我想从我的字典中打印前 5 个键和值,但我不能这样做。 我正在尝试在不同的 position 中使用 while 循环,但它对我不起作用。 请帮助我,我该怎么做。
代码:
def table_dict(dictionary):
if isinstance(dictionary, str):
return '<td>'+dictionary+'</td>'
s = ['<!-- wp:table --><figure class="wp-block-table"><table><tbody>']
for key, value in dictionary.items():
s.append('<tr><td>%s</td>' % key)
# s.append('<tr><td>'+key+'</td>')
s.append('<td>%s</td>' % value)
s.append('</tr>')
s.append('</tbody></table></figure><!-- /wp:table -->')
return ''.join(s)
dictionary = {"name" : "John", "age" : 35, "height" : 65, "country:": "US", "weight": "50 KG", "nationality": "N/A"}
print(table_dict(dictionary))
您显然有一个问题,即dict
不能保证顺序 - 您可以使用ordereddict
解决这个问题。
在这种情况下,要打印前 n行(也许最好说entries ),您可以按如下方式修改代码:
def table_dict(dictionary, max_entries = 5):
if isinstance(dictionary, str):
return '<td>'+dictionary+'</td>'
s = ['<!-- wp:table --><figure class="wp-block-table"><table><tbody>']
for n, [key, value] in enumerate(dictionary.items()):
if n == max_entries:
break
s.append('<tr><td>%s</td>' % key)
# s.append('<tr><td>'+key+'</td>')
s.append('<td>%s</td>' % value)
s.append('</tr>')
s.append('</tbody></table></figure><!-- /wp:table -->')
return ''.join(s)
使用此逻辑,如果字典的元素超过max_entries
,则 output 将被截断为第一个max_entries
。
字典不包含任何行。 它包含键和值。
如果您想单独打印出可能称为行的键,则必须执行以下操作:
dictionary.pop("nationality")
for key, value in dictionary.items()
print(key, ':', value)
这就是我理解你的问题的方式,如果不是,请考虑重新描述它。
@Malo 我正在尝试获取前五个键和值。 我正在尝试使用此代码。 但它仍然显示6个结果。
def table_dict(dictionary):
if isinstance(dictionary, str):
return '<td>'+dictionary+'</td>'
s = ['<!-- wp:table --><figure class="wp-block-table"><table><tbody>']
i = 1
while i < 5:
for key, value in dictionary.items():
s.append('<tr><td>%s</td>' % key)
# s.append('<tr><td>'+key+'</td>')
s.append('<td>%s</td>' % value)
s.append('</tr>')
s.append('</tbody></table></figure><!-- /wp:table -->')
print(len(s))
return ''.join(s)
i = i + 1
print(table_dict(dicts))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.