Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Drop Keys From Dictionary
#1
Hi guys,

I got a dictionary with values ranging from 0.25 to -0.25. I am looking for a way, to automatically drop all keys that are either

0 < value < 0.1

or

0 > value > -0.1


so basically all keys' values between 0.1 and -0.1 should be dropped from the dict. Is there an easy way to do that?
Reply
#2
You could iterate over the dictionary, checking each key value and if your conditions are met append that value to a new dictionary.

I don't think you can just drop key values from an existing dictionary.
Reply
#3
That would work aswell! Can you recall a code to do that ?
Reply
#4
There's probably many ways of doing this, but personally I would use the filter() method:
ages = {"0.25": "a", "0.1":"b", "-0.03": "c", "-0.25": "d"}

def myFunc(x):
	if (not -0.1 <= float(x) <= 0.1):
		return x

ages = { k:ages[str(k)] for k in filter(myFunc, ages) }
Ages would then become: {'0.25': 'a', '-0.25': 'd'}
This could be compressed into 1 line if you wanted:
ages = { k:ages[str(k)] for k in filter(lambda x: not -0.1 <= float(x) <= 0.1, ages) }
EDIT: I read your post wrong. I didn't realise the floats were the the values and not the keys. Instead you can do this:
ages = {"1": "0.25", "2": "0.1", "3": "-0.03", "4": "-0.25"}
 
ages = { k:ages[str(k)] for k in filter(lambda x: not -0.1 <= float(ages[x]) <= 0.1, ages) }
print(ages)
which gets you:
Output:
{'1': '0.25', '4': '-0.25'}
Reply
#5
Here's another straightforward method

dictOfVals = {1: 0.2, 2: -0.1, 3: 2, 4: 0.1, 5: 0.05}

newDict=dict()
# Iterate over all the dict values
for value in dictOfVals.values():
   if value > 0.1 or value < -0.1:
     print(value)
Reply
#6
(May-30-2020, 09:55 AM)WiPi Wrote: Here's another straightforward method

dictOfVals = {1: 0.2, 2: -0.1, 3: 2, 4: 0.1, 5: 0.05}

newDict=dict()
# Iterate over all the dict values
for value in dictOfVals.values():
   if value > 0.1 or value < -0.1:
     print(value)

How would I also get the corresponding key for each value?
Reply
#7
A dictionary has a pop method:

https://docs.python.org/3/library/stdtyp...p#dict.pop Wrote:pop(key[, default])

If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
Reply
#8
Thanks, with your help I made it work!

Now, is there a convenient way to select these keys in a data frame ? E.g. if the dict gave me the keys : "a" , "b" and "e", I want to select them from the the data frame where they are initially coming from :
df = df.columns["a", "b", "e"]
I could do it manually, however I got too many returned keys and I am asking out of curiosity.
Reply
#9
Try following with pandas:
df = pd.DataFrame(columns=list("abcdefgh"))
df[["a", "b", "c"]]
In the previous question you asked how to get also the keys.
If you want to get also the keys, why not return two dicts?
One dict could hold all ok_values and the other can contain the not_ok_values.

def classify(mapping):
    """
    Return two dicts from mapping.
    The first dict contains the `ok values`
    and the second dict contains the `not ok values`
    """
    ok_mapping = {}
    nok_mapping = {}
    for key, value in mapping.items():
        if 0 < value < 0.1:
            ok_mapping[key] = value
        else:
            nok_mapping[key] = value
    return ok_mapping, nok_mapping


dictOfVals = {1: 0.2, 2: -0.1, 3: 2, 4: 0.1, 5: 0.05}
print(classify(dictOfVals))
Output:
({5: 0.05}, {1: 0.2, 2: -0.1, 3: 2, 4: 0.1})
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Adding keys and values to a dictionary giladal 3 596 Nov-19-2020, 04:58 PM
Last Post: deanhystad
  access dictionary with keys from another and write values to list redminote4dd 6 1,125 Jun-03-2020, 05:20 PM
Last Post: DeaD_EyE
  Problem adding keys/values to dictionary where keynames = "property" and "value" jasonashaw 1 778 Dec-17-2019, 08:00 PM
Last Post: jasonashaw
  Checking if the combination of two keys is in a dictionary? mrsenorchuck 6 1,450 Dec-04-2019, 10:35 AM
Last Post: mrsenorchuck
  Retrieving dictionary keys within with another dictionay bazcurtis 8 1,136 Oct-29-2019, 10:06 PM
Last Post: bazcurtis
  json.dumps to keep dictionary keys batchenr 1 831 May-14-2019, 11:17 AM
Last Post: buran
  Reference new dictionary keys with a variable slouw 4 1,127 May-07-2019, 03:30 AM
Last Post: slouw
  Get specific key from multiple keys in python dictionary pradeepkumarbe 0 924 Mar-24-2019, 07:23 PM
Last Post: pradeepkumarbe
  Most efficient way to define sub keys of a dictionary? wrybread 1 1,017 Feb-21-2019, 12:23 AM
Last Post: snippsat
  Need help for extractring keys from dictionary dragan979 3 1,403 Jan-23-2019, 02:44 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020