Dictionary Doesn;t Update the Value It Initilize to 0 Again After Increaming Python
15 things y'all should know well-nigh Dictionaries in Python
Guidelines to use dictionaries in Python
one. What is a Python dictionary?
A dictionary is an unordered and mutable Python container that stores mappings of unique keys to values. Dictionaries are written with curly brackets ({}), including cardinal-value pairs separated by commas (,). A colon (:) separates each key from its value.
Three dictionaries are shown below, containing the population of the 5 largest German cities, list of products, and pupil's grades.
2. Create a dictionary with dict() constructor
Dictionaries can also exist created with the congenital-in role dict(**kwarg). This function takes an arbitrary number of keywords arguments (arguments preceded by an identifier kwarg=value) as input.
Nosotros can also create a dictionary using another dictionary in combination with keyword arguments (dict(mapping, **kwarg)) as follows:
Alternatively, we can construct a dictionary using an iterable (e.g. list of tuples). Each tuple must contain two objects. The first object becomes the cardinal and the 2d becomes the value of the dictionary.
Lastly, nosotros tin can create a lexicon using two lists. First, nosotros have to build an iterator of tuples using zip(*iterables) function. So, we employ the dict([iterable, **kwarg]) function to construct the dictionary, as we did previously.
3. Admission values in a dictionary
To admission lexicon values, we cannot use a numeric index (equally we do with lists or tuples), since the dictionaries are unordered containers. Instead, we enclose the central using square brackets([]). If we try to access a value using an undefined key, a KeyError is raised.
To avert getting an exception with undefined keys, nosotros can employ the method dict.become(key[, default]). This method returns the value for key if key is in the dictionary, else returns default. If default is not provided, it returns None (but never raises an exception).
4. Insert elements in a dictionary
To insert an element in a dictionary, we tin use square brackets as follows:
To insert multiple items at once, we can use the method dict.update([other]). This method updates the dictionary with the key/value pairs from other, overwriting existing keys.
Every bit shown to a higher place, the .update() method accepts as an argument not but another lexicon, simply also a listing of tuples or keyword arguments. This method modifies the dictionary in-place, returning None.
5. Change elements in a lexicon
Nosotros tin can modify the value of an item by accessing the key using square brackets ([]). To modify multiple values at in one case, we tin can utilise the .update() method, since this function overwrites existing keys.
After, we increment the price of a sofa 100 units, and we modify the grades of two students.
half dozen. Remove elements in a dictionary
To remove an element in a lexicon, we can use either the del dict[primal] keyword or the dict.pop(key[, default]) method.
The del dict[key] keyword removes the given element from the dictionary, raising a KeyError if key does not exists.
If key exists in the dictionary, the dict.pop(key[, default]) method removes the item with the given cardinal from the dictionary and returns its value. On the contrary, if key does non exist in the dictionary, the method returns the default value. If no default value is provided and key does not be, the .pop() method volition raise an exception (KeyError).
seven. Check if a central exists
To bank check whether a key exists in a dictionary, nosotros have to utilize a membership operator. Membership operators are used to test whether a value is institute in a sequence (e.g. strings, lists, tuples, sets, or dictionaries). There are ii membership operators, equally explained below.
- in → Evaluates to true if the object on the left side is included in the object on the right side.
- non in → Evaluates to truthful if the object on the left side is non included in the object on the right side.
Equally shown above, membership operators (in and not in) can be used to bank check whether a key exists in a dictionary, but they can as well be used with other sequences in the post-obit fashion.
8. Copy a lexicon
To copy a dictionary, nosotros tin only use the dict.re-create() method. This method returns a shallow re-create of the dictionary. We have to be conscientious with shallow copies, since if your dictionary contains some other container-objects like lists, tuples, or sets, they will exist referenced again and non duplicated.
To avoid this problem, we can create a deep re-create using re-create.deepcopy(x) part (defined in the copy module) as follows:
The divergence between shallow copies and deep copies is only relevant when the dictionary contains other objects like lists, since those objects volition be referenced instead of duplicated (shallow copy). To create a fully independent clone of the original dictionary, nosotros have to brand a deep re-create.
If you want to know more than about how to copy a dictionary, you can read the following article where the differences between shallow copies and deep copies are explained in detail.
Information technology is of import to bear in mind that the = operator does not make a re-create of the dictionary. It is but another name to refer to the same dictionary, significant whatever modification to the new dictionary is reflected in the original one.
ix. Determine the length of the dictionary
To determine how many primal-value pairs the dictionary contains, nosotros tin can use the len() role. This function returns the number of items of an object. The input of the part can be a dictionary, but also some other type of sequence such as a string, listing, tuple, or gear up.
10. Loop through a dictionary
Iterating through keys
To iterate over the keys, we can use the lexicon direct in a for loop as follows:
Alternatively, nosotros can employ the dict.keys() method. This method returns a view object, containing the keys of the dictionary.
Iterating through values
If you merely demand to work with the values of a lexicon, then you tin use the dict.values() method in a for loop. This method returns a view object that contains the values of the dictionary.
We can compute how many people live in the five largest German cities using dict.values() method as follows:
As we can observe, almost nine million people live in the v largest German cities.
Iterating through items
When you're working with dictionaries, it'due south likely that you lot need to apply the keys and the values. To loop through both, you can use the dict.items() method. This method returns a view object, containing central-value pairs as a listing of tuples.
We tin can determine the student with the everyman examination score using the dict.items() method in combination with a for loop as follows:
Every bit shown in a higher place, Normando is the student with the lowest examination score (2.5).
xi. Dictionary comprehensions
Python for-loops are very handy in dealing with repetitive programming tasks; however, there is another alternative to achieve the same results in a more efficient way: dictionary comprehensions.
Dictionary comprehensions let the creation of a dictionary using an elegant and simple syntax: {key: value for vars in iterable}. In addition, they are faster than traditional for-loops.
Nosotros can filter the products with a price lower than 100 euros using both a traditional for-loop and a dictionary comprehension.
As we can observe, lexicon comprehensions provide the same results equally traditional for-loops in a more than elegant fashion.
12. Nested dictionaries
Nested dictionaries are dictionaries that comprise other dictionaries. Nosotros can create a nested lexicon in the same manner nosotros create a normal lexicon using curly brackets ({}).
The following nested dictionary contains data about 5 famous works of art. Equally we can observe, the values of the lexicon are other dictionaries as well.
We can also create the prior nested dictionary using the dict() constructor, passing the key: value pairs equally keyword arguments.
To access elements in a nested dictionary, we specify the keys using multiple square brackets ([]).
If y'all desire to know more about nested dictionaries, you can read the post-obit commodity where, how to work with nested dictionaries (e.g. update items, alter elements, and loop though) is explained in detail.
13. Culling containers : OrderedDict, defaultdict, and Counter
The collections module provides culling container datatypes to congenital-in Python containers. Three dictionary subclasses contained in the collections module that are pretty handy when working with Python are: (1)OrderedDict, (2)defaultdict, and (3)Counter.
OrderedDict
OrderedDict consists of a dictionary that remembers the order in which its contents are added. In Python 3.half dozen+ dictionaries are besides insertion ordered, pregnant they remember the order of items inserted. All the same, to guarantee element club across other Python versions, nosotros have to use OrderedDict containers.
As shown above, OrderedDict accepts dictionary methods and functions. Moreover, elements can be inserted, changed, or deleted in the aforementioned way as with normal dictionaries.
defaultdict
Defaultdicts are a dictionary subclass that assign a default value when a key is missing (it has not been set yet). They never raise a KeyError, if nosotros try to access an particular that is not available in the dictionary, instead a new entry is created.
Defaultdicts take a part as an argument, and initialize the missing key with the value returned past the function. In the case beneath, the keys are initialized with different values, depending on the function employed every bit first statement.
As nosotros tin observe, we can pass a dictionary or keywords every bit 2d argument (optional) to initialize the defaultdict container.
Counter
A Counter is a dictionary bracket for counting hastable objects. The office returns a Counter object, where elements are stored every bit keys and their counts are stored every bit values. Using this office, we can hands count the elements of a list, every bit shown beneath.
As shown above, we can easily obtain the nearly frequent elements with the .most_common([northward]) method. This method returns a list of the n most common elements and their counts.
14. Create a Pandas DataFrame from a dictionary.
A Pandas DataFrame is a two-dimensional tabular information where each row represents an ascertainment and each column a variable. A Pandas DataFrame tin can be created using the pandas.DataFrame constructor. This function accepts equally input diverse python containers (e.g. lists, dictionaries, or numpy arrays). Withal, in this article, we explain merely the ways to create a DataFrame that involve the use of dictionaries.
Create a DataFrame from a lexicon
We tin can create a DataFrame from a dictionary, where the keys represent column names, and the values represent column data in the following manner:
Every bit nosotros tin detect, the default index is just the row number (an integer index beginning at 0). We tin modify these indexes by passing the index list to the DataFrame constructor.
Create a DataFrame from a listing of dictionaries
A listing of dictionaries can also be used to create a DataFrame, where the keys represent column names. As earlier, we can alter indexes by passing the alphabetize list to the DataFrame office.
15. Functions in Pandas that utilise dictionaries
There are several functions in Pandas that use dictionaries as input values, for example, pandas.DataFrame.rename and pandas.DataFrame.supplant.
pandas.DataFrame.rename
This office returns a DataFrame with renamed axis labels. We can use a dictionary as input where keys refer to the one-time names and values to the new ones. Labels non contained in the dictionary remain unchanged.
Every bit shown higher up, we can change index labels, providing a dictionary to the index parameter. Alternatively, nosotros can modify column names providing the dictionary to the cavalcade parameter.
pandas.DataFrame.supervene upon
This function replaces values of the DataFrame with other values dynamically. We tin use a dictionary with the replace function to alter the DataFrame where keys represent existing entries, and values replacement entries.
Article finished! 🍀 Equally you lot can run across, dictionaries are a really useful tool in Python. I promise this article serves you as a guideline for taking full advantage of them when coding in Python. 💪
valerioinglacrievor.blogspot.com
Source: https://towardsdatascience.com/15-things-you-should-know-about-dictionaries-in-python-44c55e75405c
0 Response to "Dictionary Doesn;t Update the Value It Initilize to 0 Again After Increaming Python"
Post a Comment