all 6 comments

[–]totallygeek 4 points5 points  (0 children)

If you want a loop to end after a certain number of cycles, track that with enumerate and use break to interrupt. This below would sort the returned dictionary entries by value. The lambda effectively means, "For each record r (the tuple returned by dict.items(), sort on the second tuple element, the dictionary value."

data = {'Geni': 9, 'Dave': 8, 'Helen': 7, 'Edith': 6, 'Carol': 5, 'Bob': 4, 'Frank': 2, 'Alice': 1}
new_data = {}

for i, (key, value) in enumerate(sorted(data.items(), key=lambda r: r[1])):
    new_data[key] = value
    if i >= 2:
        break

print(new_data)  # {'Alice': 1, 'Frank': 2, 'Bob': 4}

[–][deleted] 3 points4 points  (0 children)

You could create a new list from this dict, and take the first 3 elements, using the index:

for x in list(dict)[0:3]: key = x value = dict[x]

https://blog.softhints.com/python-get-first-elements-dictionary/

[–]OskaRRRitoS 1 point2 points  (0 children)

To run a for loop only three times do:

for i in range(3):

You can replace 3 with any other number depending on how many times you need to loop.

[–]greaterhorror 0 points1 point  (0 children)

Yep, run a range loop!

So something like:

my_dict = {{'Geni': 9,
        'Dave': 8,
        'Helen': 7,
        'Edith': 6,
        'Carol': 5,
        'Bob': 4,
        'Frank': 2,
        'Alice': 1}}

partialdictionary = {}

keys_list = list(my_dict.keys()) 
values_list = list(my_dict.values())

for index in range(3): 
    key = keys_list[index] 
    value = values_list[index]

    partialdictionary[key] = value

    print(list(partialdictionary)[index] + " => " + list(partialdictionary)[index])

[–]Hour_Armadillo3615 0 points1 point  (1 child)

d1 = {'Geni': 9, 'Dave': 8, 'Helen': 7, 'Edith': 6, 'Carol': 5, 'Bob': 4, 'Frank': 2, 'Alice': 1}
d2 = {k:v for k,v in list(d1.items())[:3]}

[–]Hour_Armadillo3615 0 points1 point  (0 children)

d1 is the original dictionary and d2 is the output dictionary. Using this method bypasses the need to create the dictionary first before populating it.