-3

I want to print first 5 keys and values from my dictionary but I can't do that. I'm trying with while loop in different position but it's not working for me. Please help me how can I do that.

Code:

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))
Mi Monir
  • 1
  • 3

2 Answers2

0

You have clearly the problem that order is not guaranteed in dict - you could solve that using an ordereddict.

Under that scenario, to print the first n lines (maybe it is better to say entries), you could modify your code as follows:

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)

Using this logic, if a dictionary has more than max_entries element, the output will be truncated to the first max_entries.

nikeros
  • 3,302
  • 2
  • 10
  • 26
0

A dictionary does not contain any rows. It contains of keys and values.

If you want to print out the keys separately which you might refer as rows you have to do:

dictionary.pop("nationality")
for key, value in dictionary.items()
    print(key, ':', value)

This is how I understand your problem, if not please consider redescribing it.

nikeros
  • 3,302
  • 2
  • 10
  • 26
Adam
  • 43
  • 1
  • 7