Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shorthand way to create dictionary key if it does not exist

Tags:

python

I have a dictionary of zoo animals. I want to put it into the dictionary in a nested dictionary but get a KeyError because that particular species has not been added to the dictionary.

def add_to_world(self, species, name, zone = 'retreat'):
    self.object_attr[species][name] = {'zone' : zone}

Is there a shortcut to checking if that species is in the dictionary and create it if it is not or do i have to do it the long way and manually check if that species has been added?

like image 919
user1082764 Avatar asked Jun 01 '12 01:06

user1082764


People also ask

What does dict return if key doesn't exist?

The get() method is a dictionary method that returns the value of the associated key. If the key is not present it returns either a default value (if passed) or it returns None. Using this method we can pass a key and check if a key exists in the python dictionary.

How do you add a key to a dictionary Python if not exists?

Add an item only when the key does not exist in dict in Python (setdefault()) In Python, you can add a new item to the dictionary dict with dict_object[key] = new_value . In this way, if the key already exists, the value is updated (overwritten) with the new value.

Which dictionary method sets a value if a key doesn't exist?

setdefault() method sets a dictionary key to a default value if the key does not exist in the dictionary.

How do you create an empty dictionary key?

To create an empty dictionary, first create a variable name which will be the name of the dictionary. Then, assign the variable to an empty set of curly braces, {} . Another way of creating an empty dictionary is to use the dict() function without passing any arguments.


2 Answers

def add_to_world(self, species, name, zone = 'retreat'):
    self.object_attr.setdefault(species, {})[name] = {'zone' : zone}
like image 194
kindall Avatar answered Oct 13 '22 22:10

kindall


Here's an example of using defaultdict with a dictionary as a value.

>>> from collections import defaultdict
>>> d = defaultdict(dict)
>>> d["species"]["name"] = {"zone": "1"}
>>> d
defaultdict(<type 'dict'>, {'species': {'name': {'zone': '1'}}})
>>>

If you want further nesting you'll need to make a function to return defaultdict(dict).

def nested_defaultdict():
    return defaultdict(dict)

# Then you can use a dictionary nested to 3 levels
d2 = defaultdict(nested_defaultdict)
d2["species"]["name"]["zone"] = 1
like image 32
monkut Avatar answered Oct 13 '22 22:10

monkut