A python program to filter dictionary - python

Write a python program to filter a dictionary based on values that are the multiples of 6
NOTE:
Take keys as strings and values as integers.
Constraints:
1<=number of key value pairs<=10
Sample test case: keys : a,b,c,d,e,f values:1,2,3,4,5,6 {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6} {'f':6}

You can use a dict comprehension.
d = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
res = {k:v for k,v in d.items() if v % 6 == 0}
print(res)

old_dict = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
#or this it will work totally perfect
#old_dict = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13}
print (f"Original dictionary is : {old_dict}")
print()
new_dict = {key:value for (key, value) in old_dict.items() if value % 6 == 0}
print(f"New dictionary with multiple of 6 is : {new_dict}")

Related

inversing a dictionary in python with duplicate values

I need to inverse a dictionary so that each old value will now be a key and the old keys will be the new values.
The trick is that there could be multiple values that are the same in the old dictionary so I need each value in the new dictionary to be a list, and if there were identical values in the old dictionary then they both will be in the list of the value of the new dictionary.
for example:
the dictionary {"python" : 1, "is" : 1, "cool" : 2}
would end up as: {1 : ["python", "is"], 2 : ["cool"]}
this is what I tried:
def inverse_dict(my_dict):
new_dict = {}
values_list = list(my_dict.values())
new_dict = new_dict.fromkeys(values_list)
for key in new_dict:
new_dict[key] = []
for old_key in my_dict:
new_dict[my_dict[old_key]] = list(new_dict[my_dict[old_key]]).append(old_key)
return new_dict
Would greatly appreciate any help with my approach (and better approaches to the problem) as I am very new to Python, thanks!
You can use dict.setdefault check if a key exists in the dictionary and if not, create new value (in this case empty list []):
d = {"python" : 1, "is" : 1, "cool" : 2}
reversed_d = {}
for k, v in d.items():
reversed_d.setdefault(v, []).append(k)
print(reversed_d)
Prints:
{1: ['python', 'is'], 2: ['cool']}
This can be more explicitly rewritten as:
d = {"python" : 1, "is" : 1, "cool" : 2}
reversed_d = {}
for k, v in d.items():
if v not in reversed_d:
reversed_d[v] = [k]
else:
reversed_d[v].append(k)
print(reversed_d)
You can use a defaultdict to avoid the pre-fill step
from collections import defaultdict
def inverse_dict(my_dict: dict):
new_dict = defaultdict(list)
for k, v in my_dict.items():
new_dict[v].append(k)
return new_dict
Though I prefer #azro's answer with the default dict, another solution is doing it with dictionary and list comprehensions.
It looks like this:
{value : [key for key in my_dict if my_dict[key] == value] for value in set(my_dict.values())}
What it does is runs over the values of the dictionary without duplicates - set(my_dict.values()).
It builds every value as a key (because it's on the left side of the ":").
And its value is a list of the keys that point to that value - [key for key in my_dict if my_dict[key] == value].

Creating and Sorting a nested dictionary

I have two arrays:-
A=[a,d,b,c]
B=[e,g,f,h,k,l,m]
I want to create a nested dictionary by combing two arrays. I want to insert hello in a nested dictionary for each key pair. Expected result :
d=dict()
d={'a':{'e':'Hello','g':'Hello','f':'Hello','f':'Hello','h':'Hello','k':'Hello','l':'Hello','m':'Hello'},
'b':{'e':'Hello','g':'Hello','f':'Hello','f':'Hello','h':'Hello','k':'Hello','l':'Hello','m':'Hello'},
c:{'e':'Hello','g':'Hello','f':'Hello','f':'Hello','h':'Hello','k':'Hello','l':'Hello','m':'Hello'} --------- }
My code :
for f in range(0,len(A)):
d[f] = {}
for i in range (0,len(B):
if A[f] not in d:
d[f]={}
d[A[f]].update([B[i]]:'Hello')
print d
But what I am getting is the distorted dictionary. I was expecting results as I explained above but I am getting result a dictionary, not in proper order and sorting is messed up.
Please Help.
OrderDict exists in python, but it does remember the order of keys insertion :
from collections import OrderedDict
d = {}
d['a'] = 1
d['b'] = 2
d['c'] = 3
for k,v in d.items():
print(k,v)
#('a',1)
#('c',3)
#('b',2)
ord = {}
ord = {}
ord['a'] = 1
ord['b'] = 2
ord['c'] = 3
for k,v in ord.items():
print(k,v)
#('a',1)
#('b',2)
#('c',3)
Official doc here

Extract all single {key:value} pairs from dictionary

I have a dictionary which maps some keys to 1 or more values.
In order to map to more than 1 value, I'm mapping each individual key to a list. How can I get the number of the single pairs? Is there a quick pythonic way to do this?
My dict looks something like this:
>>print dict
{'key1':['value11',value12, ...], 'key2': ['value21'], 'key3':['value31', 'value32']}
So in the above example, I would expect my output to be 1
With d being the dictionary:
sum(len(v) == 1 for v in d.values())
Or:
map(len, d.values()).count(1)
(The latter requires list around the map if you're using Python 3.)
You could try something like
len([_ for v in d.values() if len(v) == 1])
where d is the name of your dictionary (you should avoid using identifiers such as dict, incidentally).
Depending on your interpreter version, you might need to use itervalues instead of values.
You can use #MosesKoledoye's solution for the short (and probably a tiny bit faster) solution, or this naive version:
print(len([value for value in d.values()
if hasattr(value, '__len__') and len(value) == 1]))
Iterate through values in dictionary and count:
count = 0
for value in dic.values():
if len(value) == 1:
count += 1
print count
You could just filter your dictionary out like this:
data = {
'key1': ['value11', 'value12'],
'key2': ['value21'],
'key3': ['value31', 'value32']
}
result = filter(lambda (k, v): len(v) == 1, data.iteritems())
print result, "=>", len(result)

Dictionary get value without knowing the key

In python if I have a dictionary which has a single key value pair and if I don't know what the key might be, how can I get the value?
(and if I have a dict with more than 1 key, value pair, how can I return any one of the values without knowing any of the keys?)
You just have to use dict.values().
This will return a list containing all the values of your dictionary, without having to specify any key.
You may also be interested in:
.keys(): return a list containing the keys
.items(): return a list of tuples (key, value)
Note that in Python 3, returned value is not actually proper list but view object.
Other solution, using popitem and unpacking:
d = {"unknow_key": "value"}
_, v = d.popitem()
assert v == "value"
Further to Delgan's excellent answer, here is an example for Python 3 that demonstrates how to use the view object:
In Python 3 you can print the values, without knowing/using the keys, thus:
for item in my_dict:
print( list( item.values() )[0] )
Example:
cars = {'Toyota':['Camry','Turcel','Tundra','Tacoma'],'Ford':['Mustang','Capri','OrRepairDaily'],'Chev':['Malibu','Corvette']}
vals = list( cars.values() )
keyz = list( cars.keys() )
cnt = 0
for val in vals:
print('[_' + keyz[cnt] + '_]')
if len(val)>1:
for part in val:
print(part)
else:
print( val[0] )
cnt += 1
OUTPUT:
[_Toyota_]
Camry
Turcel
Tundra
Tacoma
[_Ford_]
Mustang
Capri
OrRepairDaily
[_Chev_]
Malibu
Corvette
That Py3 docs reference again:
https://docs.python.org/3.5/library/stdtypes.html#dict-views
Two more ways:
>>> d = {'k': 'v'}
>>> next(iter(d.values()))
'v'
>>> v, = d.values()
>>> v
'v'
One more way: looping with for/in through a dictionary we get the key(s) of the key-value pair(s), and with that, we get the value of the value.
>>>my_dict = {'a' : 25}
>>>for key in my_dict:
print(my_dict[key])
25
>>> my_other_dict = {'b': 33, 'c': 44}
>>> for key in my_other_dict:
print(my_other_dict[key])
33
44

How can you print a key given a value in a dictionary for Python?

For example lets say we have the following dictionary:
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
How can you print a certain key given its value?
print(dictionary.get('A')) #This will print 4
How can you do it backwards? i.e. instead of getting a value by referencing the key, getting a key by referencing the value.
I don't believe there is a way to do it. It's not how a dictionary is intended to be used...
Instead, you'll have to do something similar to this.
for key, value in dictionary.items():
if 4 == value:
print key
In Python 3:
# A simple dictionary
x = {'X':"yes", 'Y':"no", 'Z':"ok"}
# To print a specific key (for instance the 2nd key which is at position 1)
print([key for key in x.keys()][1])
Output:
Y
The dictionary is organized by: key -> value
If you try to go: value -> key
Then you have a few problems; duplicates, and also sometimes a dictionary holds large (or unhashable) objects which you would not want to have as a key.
However, if you still want to do this, you can do so easily by iterating over the dicts keys and values and matching them as follows:
def method(dict, value):
for k, v in dict.iteritems():
if v == value:
yield k
# this is an iterator, example:
>>> d = {'a':1, 'b':2}
>>> for r in method(d, 2):
print r
b
As noted in a comment, the whole thing can be written as a generator expression:
def method(dict, value):
return (k for k,v in dict.iteritems() if v == value)
Python versions note: in Python 3+ you can use dict.items() instead of dict.iteritems()
target_key = 4
for i in dictionary:
if dictionary[i]==target_key:
print(i)
Within a dictionary if you have to find the KEY for the highest VALUE please do the following :
Step 1: Extract all the VALUES into a list and find the Max of list
Step 2: Find the KEY for the particular VALUE from Step 1
The visual analyzer of this code is available in this link : LINK
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
lis=dictionary.values()
print(max(lis))
for key,val in dictionary.items() :
if val == max(lis) :
print("The highest KEY in the dictionary is ",key)
I think this is way easier if you use the position of that value within the dictionary.
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
# list out keys and values separately
key_list = list(dictionary.keys())
val_list = list(dictionary.values())
# print key with val 4
position = val_list.index(4)
print(key_list[position])
# print key with val 6
position = val_list.index(6)
print(key_list[position])
# one-liner
print(list(my_dict.keys())[list(my_dict.values()).index(6)])
Hey i was stuck on a thing with this for ages, all you have to do is swap the key with the value e.g.
Dictionary = {'Bob':14}
you would change it to
Dictionary ={1:'Bob'}
or vice versa to set the key as the value and the value as the key so you can get the thing you want

Categories