Inverse order of dictionary values - python

I have a python dictionary like the following:
myDict = {'cb_rdbu_4': [['202', '0', '32'], ['244', '165', '130'], ['146', '197', '222'], ['5', '113', '176']]}
I like to inverse the order of the elements in the list. So for instance for the first key value list I like to have the following order:
'cb_rdbu_4': [['5', '113', '176'], ['146', '197', '222'], ['244', '165', '130'], ['202', '0', '32']]
How do I do that?

new_dict = dict([(key,reversed(value)) for key,value in myDict.items()])
or if you want to edit it in place
for key in myDict:
myDict[key] = reversed(myDict[key])
instead of reversed(value) you can do value[::-1]

This is a easy one.
for key, val in myDict.items():
myDict[key] = myDict[key][::-1]

You want to reverse() all the values() of the dictionary:
for seq in the_dict.values():
seq.reverse()
If you are using python2 you may replace values() with itervalues() for better performance.
Note that this mutates the original dictionary. If you want to also preserve the original dictionary, you can create a new one with a dictionary comprehension:
new_dict = {key: list(reversed(value)) for key, value in original.items()}
Or:
new_dict = {key: value[::-1] for key, value in original.items()}
If you are using an older version of python that doesn't provide dictionary comprehension you can use:
new_dict = dict((key, list(reversed(value))) for key, value in original.items())

Related

how to replace a key in dict python for loop

d={"given_age":"30","given_weight":"160","given_height":6}
want to remove "given_" from each of the key,
for key,value in d.items():
new_key=re.sub(r'given_','',key)
if new_key!=key:
d[new_key]=d.pop(key)
getting below error, my intention is to change the key only, why does it complain?
RuntimeError: dictionary keys changed during iteration
It is best not to modify collections when iterating over them. Use a dict comprehension here instead.
res = {re.sub('given_','',k) : v for k, v in d.items()}
You can also use str.replace() with dict comprehensiomn
d={"given_age":"30","given_weight":"160","given_height":6}
{key.replace('given_', '') : value for key, value in d.items()}
#{'age': '30', 'weight': '160', 'height': 6}
Edit as suggested by #CrazyChucky
{key.removeprefix('given_') : value for key, value in d.items()}
#{'age': '30', 'weight': '160', 'height': 6}
If you need to do this "in-place" and only change the keys that have the "given_" prefix, you could use the update method:
d.update((k[6:],d.pop(k)) for k in d if k.startswith("given_"))

check for specific key and value pairs in two dictionaries (both dictionary has same key and value pairs)

I have two dictionaries that have the same key and value pairs. I want to compare only the specific key-value pairs and return true.
I am new to python, Please help me to write a function for the same.
The dictionaries are
A: {'id1': 'target', 'start1': '39', 'end1': '45', \
'id2': 'query', 'start2': '98', 'end2': '104'}
B: {'id1': 'target', 'start1': '39', 'end1': '45', \
'id2': 'query', 'start2': '98', 'end2': '104'}
Here I want to check if the 'start1', 'end1', 'start2' and 'end2' values are the same are not.
result = all( A[k]==B[k] for k in ('start1', 'end1', 'start2', 'end2'))
you can use a for loop:
wanted_keys = {'start1', 'end1', 'start2', 'end2'}
same = True
for k in wanted_keys:
if A.get(k) != B.get(k):
same = False
break
one line code:
all(A.get(k) == B.get(k) for k in wanted_keys)

How to effectively perform math functions like average on values of 2 separate dictionaries

dict1 = {'Sammy Student': '65', 'Betty Student1': '45', 'Alice Student2': '100', 'tom Student3': '50', 'Varun Student4': '90'}
dict2 = {'Sammy Student': '85', 'Betty Student1': '65', 'Alice Student2': '90', 'tom Student3': '60', 'Varun Student4': '100'}
Currently i'm doing it like:
dict3 = {'Sammy Student' , (int(dict1['Sammy Student']) + int(dict2['Sammy Student']))/2}
So wanted to know if there is a more optimized/effective way of doing this?
Do it like that instead:
dict3 = {k: (int(v) + int(dict2.get(k, '0')))/2 for k, v in dict1.items()}
this is a dictionary-comprehension that loops through the key-value pairs of dict1 and for every one of those keys fetches the corresponding value from dict2 too. It converts both to integers and derives their average.
Note the .get(..) method used instead of the dict2[k] that makes sure no error is raised if a key is missing from dict2 but present in dict1.

Selecting K largest values in a dictionary of dictionary in python

I have a dictionary of dictionary as below:
ls = [{'0': {'1': '1','2': '0.5','3': '1'},'1': {'0': '0.2','2': '1','3': '0.8'},}]
I would like to select k-largest values with their keys for each key of dictionary (ls). I have written below commands. It just gives me the k-largest keys without their values.
Python Code:
import heapq
k=2
for dic in ls:
for key in dic:
print(heapq.nlargest(k, dic[key], key=dic[key].get))
Output
['2', '3']
['3', '1']
I need to have value of each selected key.
First of all, I just wanted to check why you have
ls = [{'0': {'1': '1','2': '0.5','3': '1'},'1': {'0': '0.2','2': '1','3': '0.8'},}]
This is a list containing a dict, which doesn't match your description in the question.
Here is a solution that uses dict comprehensions that should give you what you want :)
def get_n_largest_vals(n, d):
x = {key: heapq.nlargest(len, map(int, d[key])) for key in d}
return {key: map(str, x[key]) for key in x}
Here it is being used for your problem:
ls = [{'0': {'1': '1','2': '0.5','3': '1'},'1': {'0': '0.2','2': '1','3': '0.8'},}]
d = ls[0]
get_n_largest_vals(2, d)
>>> {'0': ['3', '2'], '1': ['3', '2']}
How about:
from operator import itemgetter
for d in ls:
for key, d2 in d.items():
print(dict(heapq.nlargest(k, d2.items(), key=itemgetter(1))))
Notice that your values are still strings so they'd be lexically ordered, which is not what you want, because '2' > 12' And the dictionary is not ordered!

Converting Dict Keys and Searching Them

I have a dict that's like
dict1 = {'Lou': ['Male', '15', '2'],'Jen':['Female','10','3']...and more}
Im trying to search for values greater than 14 in the 2nd part of the list and then print out the key/value. I understand that I have to convert the strings to an integer and I believe I have to iterate by doing a dict1.values method however I'm unsure of how to specify the 2nd value in the list.
You can use dict1.items to iterate through key and values at the same time:
for key, value in dict1.items():
if int(value[1]) > 14:
print key, value
For each value you get the second part with value[1], you convert it to an integer with int and then you perform your check. When the check is successful, we print both key and value, as we have access to them.
You could use dict_comprehension.
>>> dict1 = {'Lou': ['Male', '15', '2'],'Jen':['Female','10','3']}
>>> {x:y for x,y in dict1.items() if int(y[1]) > 14}
{'Lou': ['Male', '15', '2']}
you need to use dict.items it will give you a tuple containing key/value pair.
Using filter and lambda:
>>> my_dict = {'Lou': ['Male', '15', '2'],'Jen':['Female','10','3']}
>>> filter(lambda x:int(x[1][1])>14, my_dict.items())
[('Lou', ['Male', '15', '2'])]
using Keys:
>>> {x:my_dict[x] for x in my_dict if int(my_dict[x][1])>14}
{'Lou': ['Male', '15', '2']}

Categories