Home > Software engineering >  How to returns a list of all values corresponding to keys greater than x in the dictionary
How to returns a list of all values corresponding to keys greater than x in the dictionary

Time:03-02

I need to use for For loop to find the return the list of values in a dictionary greater than x.

d= {}
for key in d():
    if key > x:
        return(d(key))

CodePudding user response:

x = 20
greater_than_x = []
d = {"a": 10, "b": 20, "c": 30}


for key in d:
    if d[key] > x:
        greater_than_x.append(d[key])

print(greater_than_x)

>[30]

CodePudding user response:

d = dict(a=1, b=10, c=30, d=2)
>>> d
{'a': 1, 'c': 30, 'b': 10, 'd': 2}   

d = dict((k, v) for k, v in d.items() if v >= 10)
>>> d    
{'c': 30, 'b': 10}

values_list = list(d.values())
>>> values_list
[30, 10]
  • Related