Python dictionary: Remove all the keys that begins with s - python

I've got a dictionary like
dic = {'s_good': 23, 's_bad': 39, 'good_s': 34}
I want to remove all the keys that begins with 's_'
So in this case first two will be removed.
Is there any efficient way to do so?

This should do it:
for k in dic.keys():
if k.startswith('s_'):
dic.pop(k)

for k in dic.keys():
if k.startswith('s_'):
del dic[k]
* EDIT *
now in python 3 , years after the original answer, keys() returns a view into the dict so you can't change the dict size.
One of the most elegant solutions is a copy of the keys:
for k in list(dic.keys()):
if k.startswith('s_'):
del dic[k]

With python 3 to avoid the error:
RuntimeError: dictionary changed size during iteration
This should do it:
list_keys = list(dic.keys())
for k in list_keys:
if k.startswith('s_'):
dic.pop(k)

You can use a dictionary comprehension:
dic = {k: v for k, v in dic.items() if not k.startswith("s_")}
Note that this creates a new dictionary (which you then assign back to the dic variable) rather than mutating the existing dictionary.

How about something like this:
dic = dict( [(x,y) for x,y in dic.items() if not x.startswith('s_')] )

Related

Read a string in dictionary values and replace a specific character

I have a dict in which each value is a string. In some values, this string has "-" that I would like to remove. I have been told that it is not possible to replace the values of a dict. Is that right?
mydict
'GCA_000010565.1_genomic Ribosomal_L10:': '-TRAEKEAIIQELKEKFKEARVAVLADYRGLNV-------AEATRLRRRLREAGCEFKVAKNTLTGLAARQAGLE-----GLDPYLEGPIAIAFG-VDPVAPAKVLSDF--',
I would wish something like
mydict
'GCA_000010565.1_genomic Ribosomal_L10:': 'TRAEKEAIIQELKEKFKEARVAVLADYRGLNVAEATRLRRRLREAGCEFKVAKNTLTGLAARQAGLEGLDPYLEGPIAIAFGVDPVAPAKVLSDF',
Absolutly you can, just iterate over the mappings key/value, and change the associated value by the processed one
d = {'superkey': "foo--bar", 'superkey2': "--foo--bar",
'GCA_000010565.1_genomic Ribosomal_L10:': '-TRAEKEAIIQELKEKFKEARVAVLADYRGLNV-------AEATRLRRRLREAGCEFKVAKNTLTGLAARQAGLE-----GLDPYLEGPIAIAFG-VDPVAPAKVLSDF--', }
# LOOP version
for k, v in d.items():
d[k] = v.replace("-", "")
# DICT COMPREHENSION version
d = {k: v.replace("-", "") for k, v in d.items()}
print(d) # {'superkey': 'foobar', 'superkey2': 'foobar',
'GCA_000010565.1_genomic Ribosomal_L10:': 'TRAEKEAIIQELKEKFKEARVAVLADYRGLNVAEATRLRRRLREAGCEFKVAKNTLTGLAARQAGLEGLDPYLEGPIAIAFGVDPVAPAKVLSDF'}
Yes it is possible. You can simply use
mydict['GCA_000010565.1_genomic Ribosomal_L10:'] = mydict['GCA_000010565.1_genomic Ribosomal_L10:'].replace("-","")
No, you've been told BS. The solution:
for k in mydict:
mydict[k] = mydict[k].replace('-', '')

Python: How to combine two dictionaries in python such that the resultant contains key as the value from the first

I have two dictionaries as follows:
mydictionary_1 = {1:'apple',2:'banana'}
mydictionary_2 = {1:50,2:30}
The resultant dictionary should be such that it takes the key as the value of first dictionary.
Result_dictionary= {'apple':50, 'banana':30}
You can use a dictionary comprehension using the values of the first dictionary as the keys of the resulting dictionary. This assumes all keys of the first are present in the second dict
{v: dict2[k] for k, v in dict1.items()}
you can also add a check for the presence of the keys in the second dictionary
{v: dictionary_2[k] for k, v in dictionary_1.items() if k in dictionary_2}
Loop through one of the dictionaries and check if the value for a key in mydictionary_1 exists in mydictionary_2.
You can achieve this using python's dictionary comprehension -
Result_dictionary = { v:mydictionary_2[k] for k,v in mydictionary_1.iteritems() if k in mydictionary_2.keys()}
To see how this list comprehension is working you can even use general for loop to loop through each key, value pair in mydictionary_1
for key,value in mydictionary_1.iteritems():
if key in mydictionary_2.keys():
Result_dictionary[value]=mydictionary_2[key]
Dictionary comprehension is an ideal solution for this one, as previously mentioned. Here is a for loop example:
def combine_dictionaries(dict1, dict2):
result_dictionary = {}
for key in dict1.keys():
result_dictionary[dict1[key]] = dict2[key]
return result_dictionary
combine_dictionaries({1:'apple', 2:'banana'}, {1:50, 2:30})
>>>{'apple': 50, 'banana': 30}
This assumes all values of the dict1 are present in the dict2.
def dict_cross_match(dict1, dict2):
new_dict = {}
for item in dict1.keys():
if item in dict2.keys():
new_dict[dict1[item]] = dict2[item]
return new_dict
mydictionary_1 = {1:'apple',2:'banana'}
mydictionary_2 = {1:50,2:30}
print(dict_cross_match(mydictionary_1, mydictionary_2))

How to split list inside a dictionnary to create a new one?

I've been struggling on something for the day,
I have a dictionnary under the format
dict = {a:[element1, element2, element3], b:[element4, element5, element6]...}
I want a new dictionnary under the form
newdict = {a:element1, b:element4...}
Meaning only keeping the first element of the lists contained for each value.
You can use a dictionary comprehension:
{k: v[0] for k, v in d.items()}
# {'a': 'element1', 'b': 'element4'}
Hopefully this helps.
I like to check if the dictionary has a key before overwriting a keys value.
dict = {a:[element1, element2, element3], b:[element4, element5, element6]}
Python 2
newDict = {}
for k, v in dict.iteritems():
if k not in newDict:
# add the first list value to the newDict's key
newDick[k] = v[0]
Python 3
newDict = {}
for k, v in dict.items():
if k not in newDict:
# add the first list value to the newDict's key
newDick[k] = v[0]

removing key value pairs by matching values python

I am searching for periods "." in a dictionary and trying to delete the key/value pair if I find it
if "." in dict.values():
#delete key, value pair from the dictionary
I am sure this is very simple but I cannot seem to locate an explanation.
Thanks for your help.
Create a new dictionary without those unwanted values using dictionary comprehension. Here is an example of how to do it:
>>> old_dict = {'one': '.', 'two': 2, 'three':3, 'four':'.'}
>>> new_dict = {k:v for k,v in old_dict.iteritems() if not v == '.'}
>>> new_dict
{'three': 3, 'two': 2}
using iteritems instead of items avoids creating an intermediate list and improves performance.
If you don't want to copy your dictionary, (for example if the dictionary is large, or you have a reference to it elsewhere) then you should do it this way:
ks = [k for k in d if d[k]=='.']
for k in ks:
d.pop(k)
Create your list of keys to be removed ahead of time as shown above. You don't want to modify your dictionary while iterating over it.

Removing key values pairs from a list of dictionaries

I have a list of dictionaries such as:
[{'mykey1':'myvalue1', 'mykey2':'myvalue2'}, {'mykey1':'myvalue1a', 'mykey2':'myvalue2a'}]
I need to remove all key values pairs from all dictionaries where the key is equal to mykey1. I could do this by looping through and using the del statement, but I am wondering how I would create a new list using list comprehensions or lambdas which would just remove all key value pairs where the key was mykey1.
Many thanks
If you really want to use a list comprehension, combine it with a dict comprehension:
[{k: v for k, v in d.iteritems() if k != 'mykey1'} for d in mylist]
Substitute .iteritems() for .items() if you are on python 3.
On python 2.6 and below you should use:
[dict((k, v) for k, v in d.iteritems() if k != 'mykey1') for d in mylist]
as the {key: value ...} dict comprehension syntax was only introduced in Python 2.7 and 3.
def new_dict(old_dict):
n = old_dict.copy()
n.pop('mykey1',None)
return n
new_list_of_dict = map(new_dict,list_of_dict)
or
new_list_of_dict = [ new_dict(d) for d in list_of_dict ]
Rather than using del, I opted for dict.pop since pop will suppress the KeyError if the key doesn't exist.
If you really only want to get certain keys, this becomes a bit easier.
from operator import itemgetter
tuple_keys = ('key1','key2','key3')
get_keys = itemgetter(*tuple_keys)
new_dict_list = [ dict(zip(tuple_keys,get_keys(d)) for d in old_dict_list ]
which raises KeyError if the keys aren't in the old dict
Or:
new_dict_list = [ dict( (k,d.get(k,None)) for k in tuple_keys ) for d in old_dict_list ]
which will also add key:None if key isn't in the old dict. If you don't want that None, you could do:
new_dict_list = [ dict( (k,d[k]) for k in tuple_keys if k in d) for d in old_dict_list ]
Depending on what percent of the dictionary you're including/excluding and the size of the dictionaries, this might be slightly faster than the solution by #MartijnPieters.
You can follow this simple step :
arr = [{'mykey1':'myvalue1', 'mykey2':'myvalue2'}, {'mykey1':'myvalue1a', 'mykey2':'myvalue2a'}]
for i in arr:
del i["mykey1"]
print(arr)
output:
[{'mykey2': 'myvalue2'}, {'mykey2': 'myvalue2a'}]
On python 3.5 this works successfully
'''result is my list dict'''
[{key: value for key, value in dict.items() if key != 'EQUITY'} for dict in result]
[d.pop('mykey1', None) for d in list]

Categories