Home > database >  How do I print only the first 3 keys of a dictionary?
How do I print only the first 3 keys of a dictionary?

Time:12-15

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

I only want my code to print only the first 3 keys.

What should I change to make it work?

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.

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:

you can use a slice like this:

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

print(*list(d.keys())[:3], sep=', ')
# 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:

third_key = list(my_dict.keys())[2]
print(third_key)
  • Related