How can I filter a python dictionary by minimum value and return a new dict of values above the min value? - python-3.x

How would I filter a dictionary based on a minimum value?
grades = {"Bob": 46, "Angela":73, "Dave": 94}
I want to make a new dictionary that is only people with values above 70.
passing = {"Angela":73, "Dave":94}

It is not that complex, just follow this and you are good to go. We can do it by two ways
Using Dictionary Comprehension. Follow this link to know more about it
grades = {"Bob": 46, "Angela":73, "Dave": 94}
# new dictionary to get what you want
# using dictionary comprehension in python
passing = {key:value for key, value in grades.items() if value > 70}
print(passing)
OUTPUT
{'Angela': 73, 'Dave': 94}
Using normal approach
grades = {"Bob": 46, "Angela":73, "Dave": 94}
passing = {}
# traversing through dictionary items
for key, value in grades.items():
# check for passing values
if value > 70: passing[key] = value
print(passing)
Output will be same. What I'd suggest that start learning about Dictionary Comprehension, it is more convenient, and cleaner way to code. Happy coding :)

Try a dict comprehension to filter grades greater than 70:
>>> grades = {"Bob": 46, "Angela":73, "Dave": 94}
>>> {k: v for k, v in grades.items() if v > 70}
{'Angela': 73, 'Dave': 94}

You can use dictionary comprehension.
Store the new dictionary in the same variable
grades = {k:v for k,v in grades.items() if v > 70}
Store the new dictionary in another variable
another = {k:v for k,v in grades.items() if v > 70}
Output:
{'Angela': 73, 'Dave': 94}

Related

How to retrieve the target value key for a target value that is contained within a dictionary of lists of values without using a for loop?

I have the following dictionary. Each key contains a list of unique values:
d = {1:[10,11,12],2:[13,14],3:[15,16,17,18],4:[19],5:[20]}
I want to return the key for specified target value as per the example below (this does return the desired result).
keys = list(d.keys())
values_lst = list(d.values())
target_value = 20
for i,values in enumerate(values_lst):
if target_value in values:
index = i
keys[index]
5
However, is there a way to achieve this result without deploying the for loop (at least explicitly). The solution that I have does not feel particularly pythonic.
Thanks!
There always must be a loop somewhere, but you can do it with an one-liner:
d = {1: [10, 11, 12], 2: [13, 14], 3: [15, 16, 17, 18], 4: [19], 5: [20]}
target_value = 20
key = next(k for k, v in d.items() if target_value in v)
print(key)
Prints:
5
A more Pythonic solution, but still with an explicit for:
index = -1
for key, values in d.items():
if target_value in values:
index = key
break
print(d[index])
This may be more readable than a one-liner (as in the other answer), but YMMV.

How to sum the values inside dictionary if the values in the form of list in python

dict1 = {'Key1':[99,98,97],'Key2':[89,82,85]}
how to sum the values of key1 in python3 if the values in the format of list.
Just use sum() on the dict[key] e.g.
dict1 = {'Key1':[99,98,97],'Key2':[89,82,85]}
r = sum(dict1['Key1'])
print(r)
>> 294
Or if you mean you want to sum the first key of the dict, not necessarily 'Key1' then you can do it in a loop
dict1 = {'Key1':[99,98,97],'Key2':[89,82,85]}
for _, val_list in dict1.items(): # loop over list
r = sum(val_list) # sum the list
break
print(r)
>> 294

Python: Use a for loop to get Nth number out of a list

I need to get every 3rd value out of a list and add it to a new list.
This is what I have so far.
def make_reduced_samples(original_samples, skip):
skipped_list = []
for count in range(0, len(original_samples), skip):
skipped_list.append(count)
return skipped_list
skip is equal to 3
I get the indexes and not the value of the numbers in the list.
It gives me [0,3,6]. Which are the indexes in the list and not the value of the indexes.
The example I am given is:
In this list [12,87,234,34,98,11,9,72], you should get [12,34,9].
I cannot use skipped_list = original_samples[::3] in any way.
You need to append the value of the original_samples array at the index. Not the index (count) itself.
def make_reduced_samples(original_samples, skip):
skipped_list = []
for count in range(0, len(original_samples), skip):
skipped_list.append(original_samples[count])
return skipped_list
The correct, most pythonic, and most efficient way to do that is to use slicing.
lst = [12, 87, 234, 34, 98, 11, 9, 72]
skipped_list = lst[::3]
print(skipped_list) # [12, 34, 9]
If the step does not obey a linear relation (which it does here), then you could use a list-comprehension with enumerate to filter on the index.
skipped_list = [x for i, x in enumerate(lst) if i % 3 == 0]
print(skipped_list) # [12, 34, 9]
One liner:
skipped_list = [j for (i,j) in enumerate(original_samples, start=1) if i % 3 == 0]

Reverse Dictionary function

Hello I am having trouble making a function that reverses any dictionary given to it but without any special libraries. For example
D = {one:uno, two:dos}
would return that dictionary as D = {uno:one, dos:two}
I am asking the reverse order for both the key and value not just key, this is very different
Try this:
result = dict((v,k) for k,v in d.items())
Example:
d = {'one':'uno', 'two':'dos'}
result = dict((v,k) for k,v in d.items())
print(result) # prints - {'uno': 'one', 'dos': 'two'}
What is happening here?
(v,k) for k,v in d.items() - You first iterate over all the (key, value) pairs in the dictionary and create tuples of (value, key).
Then you call dict() to create dictionary from the tuples.

Translating for loop into list comprehension

I can get this loop to work properly:
for x in range(0,len(l)):
for k in d:
if l[x] in d[k]:
l[x] = k
This looks through a list and checks if the value is in any of the dictionary items and then calculates it equal to the dictionary key it is found within (the dictionary contains lists.)
However, I want to convert to a list comprehension or other single line statement for use in a pandas dataframe - to populate a field based on whether or not another field's value is in the labeled dictionary keys and assign it the dictionary key value.
Here is my best attempt, but it does not work:
l = [ k for x in range(0,len(l)) if l[x] in d[k] for k in d ]
Thanks
Assuming I understand what you're after (example data that can be copied and pasted is always appreciated), I'd do something like this:
>>> l = ["a", "b", "c", "d"]
>>> d = {1: ["a"], 3: ["d", "c"]}
>>> l2 = [next((k for k,v in d.items() if lx in v), lx) for lx in l]
>>> l2
[1, 'b', 3, 3]
Don't forget to think about what behaviour you want if an entry in l is found in multiple lists in d, of course, although that may not be an issue with your data.
You can't do it with a list comprehension, because you have an assignment:
l[x] = k
which is an statement, and a list comprehension can't have them.

Resources