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']}
Related
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_"))
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)
I have a dictionary:
{'dict': [['IE', '5', '-5'], ['UK', '3', '-9']]}
I wish to pop the list values that are outside of the UK, therefore taking the first value within the lists and comparing to see if it is equal to 'UK'.
I currently have:
for k,v in insideUK.items():
for i in v:
if i[0] == "UK":
print(x)
else:
k.pop(v)
I know after the else is wrong but need help!
I wish for the dict to look like this once finished popping values that aren't equal to "UK".
{'dict': [['UK', '3', '-9']]}
You can use a list comprehension to filter out based on the first element
>>> data = {'dict': [['IE', '5', '-5'], ['UK', '3', '-9']]}
>>> {'dict': [i for i in data['dict'] if i[0] == 'UK']}
{'dict': [['UK', '3', '-9']]}
You can also do it using the filter function:
d = {'dict': list(filter(lambda i: 'UK' in i, d['dict']))}
print(d)
Output:
{'dict': [['UK', '3', '-9']]}
A nested dict and list expression can do this:
{k: [i for i in v if i[0] == 'UK'] for k,v in insideUK.items()}
If you really want to do it with a for-loop and change the list in-place, you could do something like this:
for k,v in insideUK.items():
for i in v:
if i[0] == "UK":
print(x)
else:
v.remove(i)
But it is discouraged strongly to change the list you are iterating over during the iteration
d = {'Name1': ['Male', '18'],
'Name2': ['Male', '16'],
'Name3': ['Male', '18'],
'Name4': ['Female', '18'],
'Name5': ['Female', '18']}
I am trying to find a way to isolate the duplicate keys to a list if any. Like:
['Name1', 'Name3']
['Name4', 'Name5']
How can I achieve this? Thanks
An imperative solution would be to just iterate over the dictionary and add the items into another dictionary that uses the gender-age-tuple as a key, for example:
# using a defaultdict, which automatically adds an empty list for missing keys when first accesses
from collections import defaultdict
by_data = defaultdict(list)
for name, data in d.items():
# turn the data into something immutable, so it can be used as a dictionary key
data_tuple = tuple(data)
by_data[data_tuple].append(name)
the result will be:
{('Female', '18'): ['Name4', 'Name5'],
('Male', '16'): ['Name2'],
('Male', '18'): ['Name1', 'Name3']})
You can filter out entries with only one value, if you are only interested in duplicates
try this:
d = {'Name1': ['Male', '18'],
'Name2': ['Male', '16'],
'Name3': ['Male', '18'],
'Name4': ['Female', '18'],
'Name5': ['Female', '18']}
ages = {} #create a dictionary to hold items with identical ages
#loop over all the items in the dictionary
for key in d.keys():
age = d[key][1]
#if the ages dictionary still does not have an item
#for the age we create an array to hold items with the same age
if(age not in ages.keys()):
ages[age] = []
ages[age].append(key) #finally append items with the same ages together
#loop over all the items in the ages dictionary
for value in ages.values():
if(len(value) > 1):#if we have more than one item in the ages dictionary
print(value) #print it
I'm guessing you meant duplicate values and not keys, in which case you could do this with pandas:
import pandas as pd
df = pd.DataFrame(d).T #load the data into a dataframe, and transpose it
df.index[df.duplicated(keep = False)]
df.duplicated(keep = False) gives you a series of True/False, where the value is True whenever that item has a duplicate, and False otherwise. We use that to index the row names, which is 'Name1','Name2', etc.
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())