Python create dictionary

Python create dictionary DEFAULT

5. Data Structures¶

This chapter describes some things you’ve learned about already in more detail, and adds some new things as well.

5.1. More on Lists¶

The list data type has some more methods. Here are all of the methods of list objects:


Add an item to the end of the list. Equivalent to .


Extend the list by appending all the items from the iterable. Equivalent to .

(i, x)

Insert an item at a given position. The first argument is the index of the element before which to insert, so inserts at the front of the list, and is equivalent to .


Remove the first item from the list whose value is equal to x. It raises a if there is no such item.


Remove the item at the given position in the list, and return it. If no index is specified, removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)


Remove all items from the list. Equivalent to .

(x[, start[, end]])

Return zero-based index in the list of the first item whose value is equal to x. Raises a if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.


Return the number of times x appears in the list.

(*, key=None, reverse=False)

Sort the items of the list in place (the arguments can be used for sort customization, see for their explanation).


Reverse the elements of the list in place.


Return a shallow copy of the list. Equivalent to .

An example that uses most of the list methods:

>>> fruits=['orange','apple','pear','banana','kiwi','apple','banana']>>> fruits.count('apple')2>>> fruits.count('tangerine')0>>> fruits.index('banana')3>>> fruits.index('banana',4)# Find next banana starting a position 46>>> fruits.reverse()>>> fruits['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']>>> fruits.append('grape')>>> fruits['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']>>> fruits.sort()>>> fruits['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']>>> fruits.pop()'pear'

You might have noticed that methods like , or that only modify the list have no return value printed – they return the default . 1 This is a design principle for all mutable data structures in Python.

Another thing you might notice is that not all data can be sorted or compared. For instance, doesn’t sort because integers can’t be compared to strings and None can’t be compared to other types. Also, there are some types that don’t have a defined ordering relation. For example, isn’t a valid comparison.

5.1.1. Using Lists as Stacks¶

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use . To retrieve an item from the top of the stack, use without an explicit index. For example:

>>> stack=[3,4,5]>>> stack.append(6)>>> stack.append(7)>>> stack[3, 4, 5, 6, 7]>>> stack.pop()7>>> stack[3, 4, 5, 6]>>> stack.pop()6>>> stack.pop()5>>> stack[3, 4]

5.1.2. Using Lists as Queues¶

It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

To implement a queue, use which was designed to have fast appends and pops from both ends. For example:

>>> fromcollectionsimportdeque>>> queue=deque(["Eric","John","Michael"])>>> queue.append("Terry")# Terry arrives>>> queue.append("Graham")# Graham arrives>>> queue.popleft()# The first to arrive now leaves'Eric'>>> queue.popleft()# The second to arrive now leaves'John'>>> queue# Remaining queue in order of arrivaldeque(['Michael', 'Terry', 'Graham'])

5.1.3. List Comprehensions¶

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

For example, assume we want to create a list of squares, like:

>>> squares=[]>>> forxinrange(10):... squares.append(x**2)...>>> squares[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Note that this creates (or overwrites) a variable named that still exists after the loop completes. We can calculate the list of squares without any side effects using:


or, equivalently:


which is more concise and readable.

A list comprehension consists of brackets containing an expression followed by a clause, then zero or more or clauses. The result will be a new list resulting from evaluating the expression in the context of the and clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal:

>>> [(x,y)forxin[1,2,3]foryin[3,1,4]ifx!=y][(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

and it’s equivalent to:

>>> combs=[]>>> forxin[1,2,3]:... foryin[3,1,4]:... ifx!=y:... combs.append((x,y))...>>> combs[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Note how the order of the and statements is the same in both these snippets.

If the expression is a tuple (e.g. the in the previous example), it must be parenthesized.

>>> vec=[-4,-2,0,2,4]>>> # create a new list with the values doubled>>> [x*2forxinvec][-8, -4, 0, 4, 8]>>> # filter the list to exclude negative numbers>>> [xforxinvecifx>=0][0, 2, 4]>>> # apply a function to all the elements>>> [abs(x)forxinvec][4, 2, 0, 2, 4]>>> # call a method on each element>>> freshfruit=[' banana',' loganberry ','passion fruit ']>>> [weapon.strip()forweaponinfreshfruit]['banana', 'loganberry', 'passion fruit']>>> # create a list of 2-tuples like (number, square)>>> [(x,x**2)forxinrange(6)][(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]>>> # the tuple must be parenthesized, otherwise an error is raised>>> [x,x**2forxinrange(6)] File "<stdin>", line 1, in <module> [x, x**2 for x in range(6)] ^SyntaxError: invalid syntax>>> # flatten a list using a listcomp with two 'for'>>> vec=[[1,2,3],[4,5,6],[7,8,9]]>>> [numforeleminvecfornuminelem][1, 2, 3, 4, 5, 6, 7, 8, 9]

List comprehensions can contain complex expressions and nested functions:

>>> frommathimportpi>>> [str(round(pi,i))foriinrange(1,6)]['3.1', '3.14', '3.142', '3.1416', '3.14159']

5.1.4. Nested List Comprehensions¶

The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.

Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4:

>>> matrix=[... [1,2,3,4],... [5,6,7,8],... [9,10,11,12],... ]

The following list comprehension will transpose rows and columns:

>>> [[row[i]forrowinmatrix]foriinrange(4)][[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

As we saw in the previous section, the nested listcomp is evaluated in the context of the that follows it, so this example is equivalent to:

>>> transposed=[]>>> foriinrange(4):... transposed.append([row[i]forrowinmatrix])...>>> transposed[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

which, in turn, is the same as:

>>> transposed=[]>>> foriinrange(4):... # the following 3 lines implement the nested listcomp... transposed_row=[]... forrowinmatrix:... transposed_row.append(row[i])... transposed.append(transposed_row)...>>> transposed[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

In the real world, you should prefer built-in functions to complex flow statements. The function would do a great job for this use case:

>>> list(zip(*matrix))[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

See Unpacking Argument Lists for details on the asterisk in this line.

5.2. The statement¶

There is a way to remove an item from a list given its index instead of its value: the statement. This differs from the method which returns a value. The statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice). For example:

>>> a=[-1,1,66.25,333,333,1234.5]>>> dela[0]>>> a[1, 66.25, 333, 333, 1234.5]>>> dela[2:4]>>> a[1, 66.25, 1234.5]>>> dela[:]>>> a[]

can also be used to delete entire variables:

Referencing the name hereafter is an error (at least until another value is assigned to it). We’ll find other uses for later.

5.3. Tuples and Sequences¶

We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two examples of sequence data types (see Sequence Types — list, tuple, range). Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the tuple.

A tuple consists of a number of values separated by commas, for instance:

>>> t=12345,54321,'hello!'>>> t[0]12345>>> t(12345, 54321, 'hello!')>>> # Tuples may be nested:... u=t,(1,2,3,4,5)>>> u((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))>>> # Tuples are immutable:... t[0]=88888Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: 'tuple' object does not support item assignment>>> # but they can contain mutable objects:... v=([1,2,3],[3,2,1])>>> v([1, 2, 3], [3, 2, 1])

As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists.

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of ). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:

>>> empty=()>>> singleton='hello',# <-- note trailing comma>>> len(empty)0>>> len(singleton)1>>> singleton('hello',)

The statement is an example of tuple packing: the values , and are packed together in a tuple. The reverse operation is also possible:

This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.

5.4. Sets¶

Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

Curly braces or the function can be used to create sets. Note: to create an empty set you have to use , not ; the latter creates an empty dictionary, a data structure that we discuss in the next section.

Here is a brief demonstration:

>>> basket={'apple','orange','apple','pear','orange','banana'}>>> print(basket)# show that duplicates have been removed{'orange', 'banana', 'pear', 'apple'}>>> 'orange'inbasket# fast membership testingTrue>>> 'crabgrass'inbasketFalse>>> # Demonstrate set operations on unique letters from two words...>>> a=set('abracadabra')>>> b=set('alacazam')>>> a# unique letters in a{'a', 'r', 'b', 'c', 'd'}>>> a-b# letters in a but not in b{'r', 'd', 'b'}>>> a|b# letters in a or b or both{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}>>> a&b# letters in both a and b{'a', 'c'}>>> a^b# letters in a or b but not both{'r', 'd', 'b', 'm', 'z', 'l'}

Similarly to list comprehensions, set comprehensions are also supported:

>>> a={xforxin'abracadabra'ifxnotin'abc'}>>> a{'r', 'd'}

5.5. Dictionaries¶

Another useful data type built into Python is the dictionary (see Mapping Types — dict). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like and .

It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: . Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with . If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.

Performing on a dictionary returns a list of all the keys used in the dictionary, in insertion order (if you want it sorted, just use instead). To check whether a single key is in the dictionary, use the keyword.

Here is a small example using a dictionary:

>>> tel={'jack':4098,'sape':4139}>>> tel['guido']=4127>>> tel{'jack': 4098, 'sape': 4139, 'guido': 4127}>>> tel['jack']4098>>> deltel['sape']>>> tel['irv']=4127>>> tel{'jack': 4098, 'guido': 4127, 'irv': 4127}>>> list(tel)['jack', 'guido', 'irv']>>> sorted(tel)['guido', 'irv', 'jack']>>> 'guido'intelTrue>>> 'jack'notintelFalse

The constructor builds dictionaries directly from sequences of key-value pairs:

>>> dict([('sape',4139),('guido',4127),('jack',4098)]){'sape': 4139, 'guido': 4127, 'jack': 4098}

In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:

>>> {x:x**2forxin(2,4,6)}{2: 4, 4: 16, 6: 36}

When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

>>> dict(sape=4139,guido=4127,jack=4098){'sape': 4139, 'guido': 4127, 'jack': 4098}

5.6. Looping Techniques¶

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the method.

>>> knights={'gallahad':'the pure','robin':'the brave'}>>> fork,vinknights.items():... print(k,v)...gallahad the purerobin the brave

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the function.

>>> fori,vinenumerate(['tic','tac','toe']):... print(i,v)...0 tic1 tac2 toe

To loop over two or more sequences at the same time, the entries can be paired with the function.

>>> questions=['name','quest','favorite color']>>> answers=['lancelot','the holy grail','blue']>>> forq,ainzip(questions,answers):... print('What is your {0}? It is {1}.'.format(q,a))...What is your name? It is lancelot.What is your quest? It is the holy grail.What is your favorite color? It is blue.

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the function.

>>> foriinreversed(range(1,10,2)):... print(i)...97531

To loop over a sequence in sorted order, use the function which returns a new sorted list while leaving the source unaltered.

>>> basket=['apple','orange','apple','pear','orange','banana']>>> foriinsorted(basket):... print(i)...appleapplebananaorangeorangepear

Using on a sequence eliminates duplicate elements. The use of in combination with over a sequence is an idiomatic way to loop over unique elements of the sequence in sorted order.

>>> basket=['apple','orange','apple','pear','orange','banana']>>> forfinsorted(set(basket)):... print(f)...applebananaorangepear

It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.

>>> importmath>>> raw_data=[56.2,float('NaN'),51.7,55.3,52.5,float('NaN'),47.8]>>> filtered_data=[]>>> forvalueinraw_data:... ifnotmath.isnan(value):... filtered_data.append(value)...>>> filtered_data[56.2, 51.7, 55.3, 52.5, 47.8]

5.7. More on Conditions¶

The conditions used in and statements can contain any operators, not just comparisons.

The comparison operators and check whether a value occurs (does not occur) in a sequence. The operators and compare whether two objects are really the same object. All comparison operators have the same priority, which is lower than that of all numerical operators.

Comparisons can be chained. For example, tests whether is less than and moreover equals .

Comparisons may be combined using the Boolean operators and , and the outcome of a comparison (or of any other Boolean expression) may be negated with . These have lower priorities than comparison operators; between them, has the highest priority and the lowest, so that is equivalent to . As always, parentheses can be used to express the desired composition.

The Boolean operators and are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if and are true but is false, does not evaluate the expression . When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument.

It is possible to assign the result of a comparison or other Boolean expression to a variable. For example,

>>> string1,string2,string3='','Trondheim','Hammer Dance'>>> non_null=string1orstring2orstring3>>> non_null'Trondheim'

Note that in Python, unlike C, assignment inside expressions must be done explicitly with the walrus operator. This avoids a common class of problems encountered in C programs: typing in an expression when was intended.

5.8. Comparing Sequences and Other Types¶

Sequence objects typically may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode code point number to order individual characters. Some examples of comparisons between sequences of the same type:


Note that comparing objects of different types with or is legal provided that the objects have appropriate comparison methods. For example, mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc. Otherwise, rather than providing an arbitrary ordering, the interpreter will raise a exception.



Python Dictionary

Dictionary in Python is an unordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. 

Note – Keys in a dictionary don’t allow Polymorphism.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Disclamer: It is important to note that Dictionaries have been modified to maintain insertion order with the release of Python 3.7, so they are now ordered collection of data values.

Creating a Dictionary

In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’. Dictionary holds a pair of values, one being the Key and the other corresponding pair element being its Key:value. Values in a dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated and must be immutable

Note – Dictionary keys are case sensitive, the same name but different cases of Key will be treated distinctly. 




Dictionary with the use of Integer Keys: {1: 'Geeks', 2: 'For', 3: 'Geeks'} Dictionary with the use of Mixed Keys: {1: [1, 2, 3, 4], 'Name': 'Geeks'}

Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing to curly braces{}. 





Empty Dictionary: {} Dictionary with the use of dict(): {1: 'Geeks', 2: 'For', 3: 'Geeks'} Dictionary with each item as a pair: {1: 'Geeks', 2: 'For'}

Nested Dictionary:





{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}


Adding elements to a Dictionary

In Python Dictionary, the Addition of elements can be done in multiple ways. One value at a time can be added to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’. Updating an existing value in a Dictionary can be done by using the built-in update() method. Nested key values can also be added to an existing Dictionary. 

Note- While adding a value, if the key-value already exists, the value gets updated otherwise a new Key with the value is added to the Dictionary.







Empty Dictionary: {} Dictionary after adding 3 elements: {0: 'Geeks', 2: 'For', 3: 1} Dictionary after adding 3 elements: {0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)} Updated key value: {0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)} Adding a Nested Key: {0: 'Geeks', 2: 'Welcome', 3: 1, 5: {'Nested': {'1': 'Life', '2': 'Geeks'}}, 'Value_set': (2, 3, 4)}


Accessing elements from a Dictionary

In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets. 






Accessing a element using key: For Accessing a element using key: Geeks

There is also a method called get() that will also help in accessing the element from a dictionary.




Accessing a element using get: Geeks

Accessing an element of a nested dictionary

In order to access the value of any key in the nested dictionary, use indexing [] syntax.




{1: 'Geeks'} Geeks For

Removing Elements from Dictionary

Using del keyword

In Python Dictionary, deletion of keys can be done by using the del keyword. Using the del keyword, specific values from a dictionary as well as the whole dictionary can be deleted. Items in a Nested dictionary can also be deleted by using the del keyword and providing a specific nested key and particular key to be deleted from that nested Dictionary.

Note: The del Dict will delete the entire dictionary and hence printing it after deletion will raise an Error.





Initial Dictionary: {'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5: 'Welcome', 6: 'To', 7: 'Geeks'} Deleting a specific key: {'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5: 'Welcome', 7: 'Geeks'} Deleting a key from Nested Dictionary: {'A': {1: 'Geeks', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5: 'Welcome', 7: 'Geeks'}

Using pop() method

Pop() method is used to return and delete the value of the key specified.




Dictionary after deletion: {3: 'Geeks', 'name': 'For'} Value associated to poped key is: Geeks

Using popitem() method

The popitem() returns and removes an arbitrary element (key, value) pair from the dictionary.




Dictionary after deletion: {3: 'Geeks', 'name': 'For'} The arbitrary pair returned is: (1, 'Geeks')

 Using clear() method

All the items from a dictionary can be deleted at once by using clear() method.





Deleting Entire Dictionary: {}

Dictionary Methods 

copy()They copy() method returns a shallow copy of the dictionary.
clear()The clear() method removes all items from the dictionary.
pop()Removes and returns an element from a dictionary having the given key.
popitem()Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
get()It is a conventional method to access a value for a key.
dictionary_name.values()returns a list of all the values available in a given dictionary.
str()Produces a printable string representation of a dictionary.
update()Adds dictionary dict2’s key-values pairs to dict
setdefault()Set dict[key]=default if key is not already in dict
keys()Returns list of dictionary dict’s keys
items()Returns a list of dict’s (key, value) tuple pairs
has_key()Returns true if key in dictionary dict, false otherwise
fromkeys()Create a new dictionary with keys from seq and values set to value.
type()Returns the type of the passed variable.
cmp()Compares elements of both dict.

Recent Articles on Python Dictionary

More Videos on Python Dictionary: 
Python Dictionary Set 2 
Python Dictionary Set 3

 Dictionary Programs

Useful Links 

  1. Speaker ohms calculator
  2. American gods wiki
  3. Tiki hut backyard
  4. Hotel in compton california

Python Dictionary

Python dictionary is an unordered collection of items. Each item of a dictionary has a pair.

Dictionaries are optimized to retrieve values when the key is known.

Creating Python Dictionary

Creating a dictionary is as simple as placing items inside curly braces separated by commas.

An item has a and a corresponding that is expressed as a pair (key: value).

While the values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique.

As you can see from above, we can also create a dictionary using the built-in function.

Accessing Elements from Dictionary

While indexing is used with other data types to access values, a dictionary uses . Keys can be used either inside square brackets or with the method.

If we use the square brackets , is raised in case a key is not found in the dictionary. On the other hand, the method returns if the key is not found.


Changing and Adding Dictionary elements

Dictionaries are mutable. We can add new items or change the value of existing items using an assignment operator.

If the key is already present, then the existing value gets updated. In case the key is not present, a new (key: value) pair is added to the dictionary.


Removing elements from Dictionary

We can remove a particular item in a dictionary by using the method. This method removes an item with the provided and returns the .

The method can be used to remove and return an arbitrary item pair from the dictionary. All the items can be removed at once, using the method.

We can also use the keyword to remove individual items or the entire dictionary itself.


Python Dictionary Methods

Methods that are available with a dictionary are tabulated below. Some of them have already been used in the above examples.

clear()Removes all items from the dictionary.
copy()Returns a shallow copy of the dictionary.
fromkeys(seq[, v])Returns a new dictionary with keys from and value equal to (defaults to ).
get(key[,d])Returns the value of the . If the does not exist, returns (defaults to ).
items()Return a new object of the dictionary's items in (key, value) format.
keys()Returns a new object of the dictionary's keys.
pop(key[,d])Removes the item with the and returns its value or if is not found. If is not provided and the is not found, it raises .
popitem()Removes and returns an arbitrary item (key, value). Raises if the dictionary is empty.
setdefault(key[,d])Returns the corresponding value if the is in the dictionary. If not, inserts the with a value of and returns (defaults to ).
update([other])Updates the dictionary with the key/value pairs from , overwriting existing keys.
values()Returns a new object of the dictionary's values

Here are a few example use cases of these methods.


Python Dictionary Comprehension

Dictionary comprehension is an elegant and concise way to create a new dictionary from an iterable in Python.

Dictionary comprehension consists of an expression pair (key: value) followed by a statement inside curly braces .

Here is an example to make a dictionary with each item being a pair of a number and its square.


This code is equivalent to


A dictionary comprehension can optionally contain more for or if statements.

An optional statement can filter out items to form the new dictionary.

Here are some examples to make a dictionary with only odd items.


To learn more dictionary comprehensions, visit Python Dictionary Comprehension.

Other Dictionary Operations

Dictionary Membership Test

We can test if a is in a dictionary or not using the keyword . Notice that the membership test is only for the and not for the .


Iterating Through a Dictionary

We can iterate through each key in a dictionary using a loop.


Dictionary Built-in Functions

Built-in functions like , , , , , etc. are commonly used with dictionaries to perform different tasks.

all()Return if all keys of the dictionary are True (or if the dictionary is empty).
any()Return if any key of the dictionary is true. If the dictionary is empty, return .
len()Return the length (the number of items) in the dictionary.
cmp()Compares items of two dictionaries. (Not available in Python 3)
sorted()Return a new sorted list of keys in the dictionary.

Here are some examples that use built-in functions to work with a dictionary.




Python comes with a variety of built-in data structures, capable of storing different types of data. A Python dictionary is one such data structure that can store data in the form of key-value pairs. The values in a Python dictionary can be accessed using the keys. In this article, we will be discussing the Python dictionary in detail.

Creating a Dictionary

To create a Python dictionary, we need to pass a sequence of items inside curly braces , and separate them using a comma (,). Each item has a key and a value expressed as a "key:value" pair.

The values can belong to any data type and they can repeat, but the keys must remain unique.

The following examples demonstrate how to create Python dictionaries:

Creating an empty dictionary:

Creating a dictionary with integer keys:

Creating a dictionary with mixed keys:

We can also create a dictionary by explicitly calling the Python's method:

A dictionary can also be created from a sequence as shown below:

Dictionaries can also be nested, which means that we can create a dictionary inside another dictionary. For example:

To print the dictionary contents, we can use the Python's function and pass the dictionary name as the argument to the function. For example:


Accessing Elements

To access dictionary items, pass the key inside square brackets . For example:


We created a dictionary named . A variable named was then created and its value is set to be the value for the key "model" in the dictionary.

Here is another example:


The dictionary object also provides the function, which can be used to access dictionary elements as well. We append the function with the dictionary name using the dot operator and then pass the name of the key as the argument to the function. For example:


Now we know how to access dictionary elements using a few different methods. In the next section we'll discuss how to add new elements to an already existing dictionary.

Adding Elements

There are numerous ways to add new elements to a dictionary. We can use a new index key and assign a value to it. For example:


The new element has "Capacity" as the key and "1800CC" as its corresponding value. It has been added as the first element of the dictionary.

Here is another example. First let's first create an empty dictionary:


The dictionary returns nothing as it has nothing stored yet. Let us add some elements to it, one at a time:


To add the elements, we specified keys as well as the corresponding values. For example:

In the above example, 0 is the key while "Apples" is the value.

It is even possible for us to add a set of values to one key. For example:


In the above example, the name of the key is "Values" while everything after the sign are the actual values for that key, stored as a Set.

Other than adding new elements to a dictionary, dictionary elements can also be updated/changed, which we'll go over in the next section.

Updating Elements

After adding a value to a dictionary we can then modify the existing dictionary element. You use the key of the element to change the corresponding value. For example:


In this example you can see that we have updated the value for the key "year" from the old value of 2012 to a new value of 2014.

Removing Elements

The removal of an element from a dictionary can be done in several ways, which we'll discuss one-by-one in this section:

The keyword can be used to remove the element with the specified key. For example:


We called the keyword followed by the dictionary name. Inside the square brackets that follow the dictionary name, we passed the key of the element we need to delete from the dictionary, which in this example was "year". The entry for "year" in the dictionary was then deleted.

Another way to delete a key-value pair is to use the function and pass the key of the entry to be deleted as the argument to the function. For example:


We invoked the function by appending it with the dictionary name. Again, in this example the entry for "year" in the dictionary will be deleted.

The function removes the last item inserted into the dictionary, without needing to specify the key. Take a look at the following example:


Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

The last entry into the dictionary was "year". It has been removed after calling the function.

But what if you want to delete the entire dictionary? It would be difficult and cumbersome to use one of these methods on every single key. Instead, you can use the keyword to delete the entire dictionary. For example:


The code returns an error. The reason is that we are trying to access a dictionary which doesn't exist since it has been deleted.

However, your use-case may require you to just remove all dictionary elements and be left with an empty dictionary. This can be achieved by calling the function on the dictionary:


The code returns an empty dictionary since all the dictionary elements have been removed.

Other Common Methods

The len() Method

With this method, you can count the number of elements in a dictionary. For example:


There are three entries in the dictionary, hence the method returned 3.

The copy() Method

This method returns a copy of the existing dictionary. For example:


We created a copy of dictionary named and assigned it to the variable . If is printed on the console, you will see that it contains the same elements as those stored by dictionary.

Note that this is useful because modifications made to the copied dictionary won't affect the original one.

The items() Method

When called, this method returns an iterable object. The iterable object has key-value pairs for the dictionary, as tuples in a list. This method is primarily used when you want to iterate through a dictionary.

The method is simply called on the dictionary object name as shown below:


The object returned by can also be used to show the changes that have been implemented on the dictionary. This is demonstrated below:


The output shows that when you change a value in the dictionary, the items object is also updated to reflect this change.

The fromkeys() Method

This method returns a dictionary having specified keys and values. It takes the syntax given below:

The value for required parameter is an iterable and it specifies the keys for the new dictionary. The value for parameter is optional and it specifies the default value for all the keys. The default value for this is .

Suppose we need to create a dictionary of three keys all with the same value. We can do so as follows:


In the script above, we specified the keys and one value. The method was able to pick the keys and combine them with this value to create a populated dictionary.

The value for the parameter is mandatory. The following example demonstrates what happens when the value for the parameter is not specified:


The default value, which is , was used.

The setdefault() Method

This method is applicable when we need to get the value of the element with the specified key. If the key is not found, it will be inserted into the dictionary alongside the specified value.

The method takes the following syntax:

In this function the parameter is required. It represents the keyname of the item you need to return a value from. The parameter is optional. If the dictionary already has the key, this parameter won't have any effect. If the key doesn't exist, then the value given in this function will become the value of the key. It has a default value of .

For example:


The dictionary doesn't have the key for . The method has inserted this key and the specified a value, that is, "Gray", has been used as its value.

The following example demonstrates how the method behaves if the value for the key does exist:


The value "Allion" has no effect on the dictionary since we already have a value for the key.

The keys() Method

This method also returns an iterable object. The object returned is a list of all keys in the dictionary. And just like with the method, the returned object can be used to reflect the changes made to the dictionary.

To use this method, we only call it on the name of the dictionary, as shown below:

For example:


Often times this method is used to iterate through each key in your dictionary, like so:



This marks the end of this tutorial on Python dictionaries. These dictionaries store data in "key:value" pairs. The "key" acts as the identifier for the item while "value" is the value of the item. The Python dictionary comes with a variety of functions that can be applied for retrieval or manipulation of data. In this article, we saw how Python dictionary can be created, modified and deleted along with some of the most commonly used dictionary methods.


Dictionary python create

Create a dictionary with list comprehension

I like the Python list comprehension syntax.

Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:

You're looking for the phrase "dict comprehension" - it's actually:

Assuming is an iterable of two-tuples - you're so close. Let's create some "blahs" like that:

Dict comprehension syntax:

Now the syntax here is the mapping part. What makes this a comprehension instead of a comprehension (which is what your pseudo-code approximates) is the colon, like below:

And we see that it worked, and should retain insertion order as-of Python 3.7:

In Python 2 and up to 3.6, order was not guaranteed:

Adding a Filter:

All comprehensions feature a mapping component and a filtering component that you can provide with arbitrary expressions.

So you can add a filter part to the end:

Here we are just testing for if the last character is divisible by 2 to filter out data before mapping the keys and values.

PYTHON DICTIONARIES \u0026 FOR LOOPS (Beginner's Guide to Python Lesson 8)

Dictionary Objects

Part of the Stable ABI.

Iterate over all key-value pairs in the dictionary p. The referred to by ppos must be initialized to prior to the first call to this function to start the iteration; the function returns true for each pair in the dictionary, and false once all pairs have been reported. The parameters pkey and pvalue should either point to PyObject* variables that will be filled in with each key and value, respectively, or may be . Any references returned through them are borrowed. ppos should not be altered during iteration. Its value represents offsets within the internal dictionary structure, and since the structure is sparse, the offsets are not consecutive.

For example:

PyObject*key,*value;Py_ssize_tpos=0;while(PyDict_Next(self->dict,&pos,&key,&value)){/* do something interesting with the values... */...}

The dictionary p should not be mutated during iteration. It is safe to modify the values of the keys as you iterate over the dictionary, but only so long as the set of keys does not change. For example:


You will also be interested:

Python Dictionaries

❮ PreviousNext ❯

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964


Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and does not allow duplicates.

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

Dictionaries are written with curly brackets, and have keys and values:


Create and print a dictionary:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964

Try it Yourself »

Dictionary Items

Dictionary items are ordered, changeable, and does not allow duplicates.

Dictionary items are presented in key:value pairs, and can be referred to by using the key name.


Print the "brand" value of the dictionary:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964

Try it Yourself »

Ordered or Unordered?

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change.

Unordered means that the items does not have a defined order, you cannot refer to an item by using an index.


Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.

Duplicates Not Allowed

Dictionaries cannot have two items with the same key:


Duplicate values will overwrite existing values:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964,
  "year": 2020

Try it Yourself »

Dictionary Length

To determine how many items a dictionary has, use the function:

Dictionary Items - Data Types

The values in dictionary items can be of any data type:


String, int, boolean, and list data types:

thisdict = {
  "brand": "Ford",
  "electric": False,
  "year": 1964,
  "colors": ["red", "white", "blue"]

Try it Yourself »


From Python's perspective, dictionaries are defined as objects with the data type 'dict':

<class 'dict'>


Print the data type of a dictionary:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964

Try it Yourself »

Python Collections (Arrays)

There are four collection data types in the Python programming language:

  • List is a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered and unindexed. No duplicate members.
  • Dictionary is a collection which is ordered and changeable. No duplicate members.

When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.

❮ PreviousNext ❯


4094 4095 4096 4097 4098