Dictionary comprehensions - python

Dictionary comprehensions
num_dict={1:1,2:4,3:9}
twice_num_dict={key: (value if value*2 >=8 else None)for (key,value) in num_dict.items()}
print(twice_num_dict)
Dictionary comprehensionsi wanted to create a new dict where only key:value pairs of the existing dict will be there in the new_dict if the value*2 of the first dict was >=8 i used if and else here but idk what to type in else condition so that the key value pair of 1:1 is not printed at all

You should place your if clause after your for clause in the comprehension, like so:
{k: v for k, v in d.items() if v * 2 >= 8}

Related

filter a dictionary by key less than some range of values

I have a dictionary like this,
d = {1:'a', 2:'b', 3:'c', 4:'d'}
Now I want to filter the dictionary where the key should be more than 1 and less than 4 so the dictionary will be,
d = {2:'b', 3:'c'}
I could do this using a for loop, iterating over all the keys. but the execution time will be more looking for some fastest way to do this more efficiently in pythonic way.
you can try below code:
d = {k:v for k,v in d.items() if 1<k<4}
Pythonic way would be to use a dictionary comprehension:
{key: value for key, value in d.items() if 1 < key < 4}
It's readable enough: for each key and value in the items of the dictionary, keep those key: value pairs that have their keys between 1 and 4.
More pythonic way would be a dictionary comprehension
d = {k: v for (k, v) in d.items() if k > 1 and k < 4}
If the efficiency is a bottleneck, you may want to try to use some tree based structure instead of a dictionary that is hash based.
Python dictionaries use hashes of their keys to efficiently lookup and store data. Unfortunately, that means that they don't allow you use the numeric properties of those keys to select data (the way you might be able to do using a slice to index a list).
So I think the best way to do what you want is probably just a dictionary comprehension that tests each key against your boundary values:
d = {key: value for key, value in d.items() if 1 < key < 4}

Sorting dictionary in python by value in value

Okay so i have this dictionary:
dict = {'name':{'movie':(actualmovie), 'nreviews': (number)}, ...}
is there an easy way to order dict by the nreviews value (number) ?
No, because dicts can't be ordered.
collections.OrderedDict(sorted(D.items(), key=(lambda k, v: v['nreviews'])))

Selecting elements of a Python dictionary greater than a certain value

I need to select elements of a dictionary of a certain value or greater. I am aware of how to do this with lists, Return list of items in list greater than some value.
But I am not sure how to translate that into something functional for a dictionary. I managed to get the tags that correspond (I think) to values greater than or equal to a number, but using the following gives only the tags:
[i for i in dict if dict.values() >= x]
.items() will return (key, value) pairs that you can use to reconstruct a filtered dict using a list comprehension that is feed into the dict() constructor, that will accept an iterable of (key, value) tuples aka. our list comprehension:
>>> 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}
If you don't care about running your code on python older than version 2.7, see #opatut answer using "dict comprehensions":
{k:v for (k,v) in dict.items() if v > something}
While nmaier's solution would have been my way to go, notice that since python 2.7+ there has been a "dict comprehension" syntax:
{k:v for (k,v) in dict.items() if v > something}
Found here: Create a dictionary with list comprehension in Python. I found this by googling "python dictionary list comprehension", top post.
Explanation
{ .... } includes the dict comprehension
k:v what elements to add to the dict
for (k,v) in dict.items() this iterates over all tuples (key-value-pairs) of the dict
if v > something a condition that has to apply on every value that is to be included
You want dict[i] not dict.values(). dict.values() will return the whole list of values that are in the dictionary.
dict = {2:5, 6:2}
x = 4
print [dict[i] for i in dict if dict[i] >= x] # prints [5]

Matching lists when elements are not ordered

let's say I have a list b=['m','NN'] and a dictionary dict={'b':['NN','m','big']} and I want to use the function to retrieve the key 'b' if the elements of the list b are in dict[b]
(so let's say using [k for k,v in dict.items()].
Now how do I do that if the elements in b are not ordered as the elements in dict[b] and supposing I cannot change the order in the b list?
Thank you!
Not certain I understand what you're asking, but if what you're after is the list of keys in dictionary d with values which are super-sets of the list b, you could use something like:
b=['m','NN']
d={'b':['NN','m','big'], 'a':['jj','r']}
[k for k,v in d.items() if set(b) <= set(v)]
(I changed the name of your example dictionary as dict is a built-in class.)
You can do:
[k for k, v in dict.items() if all((x in v) for x in b)]
For example:
>>> b=['m','NN']
>>> dict={'b':['NN','m','big'], 'a':['NN', 'q']}
>>> [k for k, v in dict.items() if all((x in v) for x in b)]
['b']
(Note that it is a bad idea to name your dictionary dict, since dict is the name of the data type).

deleting entries in a dictionary based on a condition

I have a dictionary with names as key and (age, Date of Birth) tuple as the value for those keys. E.g.
dict = {'Adam' : (10, '2002-08-13'),
'Eve' : (40, '1972-08-13')}
I want to delete all the keys which have age > 30 for their age in value tuple, how can I do that? I am accessing age of each key using dict[name][0] where dict is my dictionary.
The usual way is to create a new dictionary containing only the items you want to keep:
new_data = {k: v for k, v in data.items() if v[0] <= 30}
If you need to change the original dictionary in place, you can use a for-loop:
for k, v in list(data.items()):
if v[0] > 30:
del data[k]
Note that list(data.items()) creates a shallow copy of the items of the dictionary, i.e. a new list containing references to all keys and values, so it's safe to modify the original dict inside the loop.

Categories

Resources