Home > Software engineering >  I am Trying to return a filtered dictionary from another dictionary in a function but my code is ret
I am Trying to return a filtered dictionary from another dictionary in a function but my code is ret

Time:09-02

Hi I have to filter a dictionary and return a filtered item: so in the following function i have to return the filtered dictionary if the 2nd paramenter is a part of the key or return an empty dictionary.

Not sure why my code is returning empty dictionary by default

def extractKey(dictionary, name):
    res = None
    for i in dictionary:
        if i == name:
            res = {name:dictionary[name]}
        if i != name:
            res = {}
      
    return res

CodePudding user response:

For dictionaries, keys can be tested for membership. There are a few ways you can return a single key from the dictionary as a new dict…

Using membership testing…

def extractKey(dictionary, name):
    if name in dictionary:
        return {name: dictionary[name]}

    return {}

Using .get method…

def extractKey(dictionary, name):
    value = dictionary.get(name, None)
    if value is not None:
        return {name: value}
    
    return {}

I think the first method is the cleanest and easiest to read, but there are always more than one way to do the same thing!

The second method could break in the off chance the value of the key is actually None … something to keep in mind.

In the off chance you were needing to extract multiple keys…

def extractKeys(dictionary, names):
    res = {}
    for name in names:
        if name in dictionary:
            res[name] = dictionary[name]

    return res

CodePudding user response:

I do not fully understand what your expected in/out is, but does this do something similar to what you are trying to accomplish? It returns a key-pair dictionary where the key matches the name argument.

def extractKey(dictionary, name):
    if name in dictionary:
        return {name:dictionary[name]}
    return {} 
  • Related