簡體   English   中英

如何在 Python 中為以下代碼打印字典中的前 5 個鍵和值?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM