Home > Net >  How do I print only the first 3 keys
How do I print only the first 3 keys

Time:12-09

for key, value in fre.items():
    print(key, end=', ')

I only want my code to print the first 3 keys. what should I change to make it work

CodePudding user response:

You can combine the iterator with the zip keyword to print the first 3 items.

d = {'a':1, 'b':2, 'c':3, 'd':4}

for i, (k, v) in zip(range(3), d.items()):
    print(k)

Output:

a
b
c

CodePudding user response:

count = 0
for key, value in fre.items():
    print(key, end=', ')
    count  = 1
    if count == 3:
        break

CodePudding user response:

You can use enumerate to generate indices for a sequence, with which you can break the loop when it reaches 3:

for i, k in enumerate(fre):
    if i == 3:
        break
    print(k)

Note that you don't need to call the items method if you don't need the values along with the keys. Iterating the dict itself would generate the keys.

  • Related