Add a value to a python dictionary. Dictionaries and their methods in Python

Today I will talk about a data type like dictionaries, about working with dictionaries, operations on them, methods, about dictionary generators.

Dictionaries in Python- unordered collections of arbitrary objects with access by key. They are sometimes also called associative arrays or hash tables.

To work with a dictionary, you need to create it. There are several ways to create it. First, using a literal:

>>> d = () >>> d () >>> d = ( "dict" : 1 , "dictionary" : 2 ) >>> d ( "dict" : 1 , "dictionary" : 2 )

Secondly, using the function dict:

>>> d = dict (short = "dict" , long = "dictionary" ) >>> d ("short": "dict", "long": "dictionary")>>> d = dict ([(1 , 1 ), (2 , 4 )]) >>> d (1: 1, 2: 4)

Third, using the fromkeys method:

>>> d = dict . fromkeys ([ "a" , "b" ]) >>> d ("a": None, "b": None) >>> d = dict . fromkeys ([ "a" , "b" ], 100 ) >>> d ("a": 100, "b": 100)

Fourthly, using dictionary generators, which are very similar to .

>>> d = ( a : a ** 2 for a in range (7 )) >>> d {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}

Now let's try to add entries to the dictionary and extract the key values:

>>> d = ( 1 : 2 , 2 : 4 , 3 : 9 ) >>> d [ 1 ] 2 >>> d [ 4 ] = 4 ** 2 >>> d (1: 2, 2: 4 , 3: 9, 4: 16) >>> d [ "1" ] Traceback (most recent call last):File "", line 1, in d["1"] KeyError: "1"

As you can see from the example, assignment to a new key expands the dictionary, assignment to an existing key overwrites it, and an attempt to retrieve a non-existent key throws an exception. To avoid an exception, there is a special method (see below), or you can.

What else can you do with dictionaries? Yes, the same as with other objects: , (for example, ), as well as special methods of dictionaries.

Dictionary Methods

dict.clear() - clears the dictionary.

dict.copy() - returns a copy of the dictionary.

classmethod dict.fromkeys(seq[, value]) - creates a dictionary with keys from seq and value value (None by default).

dict.get(key[, default]) - returns the value of the key, but if it does not exist, it does not throw an exception, but returns default (the default is None).

dict.items() - returns (key, value) pairs.

dict.keys() - returns the keys in the dictionary.

dict.pop(key[, default]) - removes a key and returns the value. If there is no key, returns default (throws an exception by default).

dict.popitem() - removes and returns a (key, value) pair. If the dictionary is empty, throws a KeyError exception. Remember that dictionaries are unordered.

dict.setdefault(key[, default]) - returns the value of the key, but if it does not exist, it does not throw an exception, but creates a key with the default value (None by default).

dict.update() - updates the dictionary by adding (key, value) pairs from other. Existing keys are overwritten. Returns None (not a new dictionary!).

dict.values() - returns values ​​in a dictionary.

and is an UNORDERED collection of values.


Features of dictionaries:
1. Key access. It is possible to access elements in a loop by keys.
2. Dictionary values ​​are stored in UNSORTED order, and keys may not be stored in the order in which they are added.
3. The dictionary can store nested dictionaries. Dictionary values ​​can be of any type. The key in the dictionary is an immutable type, it can be a string, an integer, a float, or a tuple consisting of the specified types.
4. Dictionaries are implemented as hash tables with quick access.
5. Dictionaries store references to objects, not the object itself.

The main operations on a dictionary are: storing with a given key and retrieving a value from it. You can also remove the pair key: value using instructions del.

Dictionary methods (functions):

  • dict()- creation of a dictionary;
  • len()- returns the number of pairs;
  • clear()- deletes all values ​​from the dictionary;
  • copy()- creates a pseudocopy of the dictionary;
  • deepcopy()- creates a complete copy of the dictionary;
  • fromkeys()- creation of a dictionary;
  • get()- get the value by key;
  • has_key()- checking the value by key;
  • items()
  • iteriyems()- returns an iterator;
  • keys()- returns a list of keys;
  • iterkeys()- returns an iterator of keys;
  • pop()- retrieves the value by key;
  • popitem()- extracts an arbitrary value;
  • update()- changes the dictionary;
  • values()- returns a list of values;
  • itervalues()- returns an iterator to a list of values.
  • in- operator, checks the presence of a value by key;
  • del- operator, deletes a pair by key;
  • dict()- constructs a dictionary using a sequence.

Using a small program as an example - phone book Let's show some operations with dictionaries:

Code: telbook = ("sasha": "32-11-4", "vanya": "44-65-99") # Declare a dictionary telbook["fedya"] = "22-47-32" # add a new object to the dictionary print telbook # Print all the values ​​of the dictionary print telbook["vanya"] # Print the number of the value "vanya" del telbook["sasha"] # delete the value "sasha" print telbook # see what happened print telbook.keys() # Print the values ​​print telbook.has_key("vanya") # check if the dictionary contains the value "vanya" Result: ("vanya": "44-65-99", "fedya": "22-47-32", " sasha": "32-11-4") 44-65-99 ("vanya": "44-65-99", "fedya": "22-47-32") ["vanya", "fedya"] True

Ways to create a dictionary:
1. By analogy with lists and tuples. Curly brackets only ():

>>> s = ("name": "Vitaliy", "age": 25) >>> s ("age": 25, "name": "Vitaliy")

2.Dynamically. As needed:

>>> s["name"] = "Vitaliy" >>> s["age"] = 26 >>> s ("age": 26, "name": "Vitaliy")

3. Using method dict(). In this case, the keys must be strings. Using this method, you can write the key without quotes. Below are four options for filling out the dictionary:

>>> s1 = dict(id = 1, name = "Vitaliy", age = 26) >>> s1 ("age": 26, "name": "Vitaliy", "id": 1) >>> s2 = dict(("id": 1, "name": "Vitaliy", "age": 26)) >>> s2 ("age": 26, "id": 1, "name": "Vitaliy") >>> s3 = dict([("id",1),("name","Vitaliy"),("age",26)]) >>> s3 ("age": 26, "id": 1, "name": "Vitaliy") >>> s4 = dict(zip(("id","name","age"),(1,"Vitaliy",26))) >>> s4 (" age": 26, "id": 1, "name": "Vitaliy")

4.using method fromkeys()— creates a dictionary from the specified list of keys with empty values.

>>> d = ().fromkeys(["name","age"],123) >>> d ("age": 123, "name": 123) or >>> d = ().fromkeys( ["name","age"]) >>> d ("age": None, "name": None)

5. Using the constructor:

>>> s = dict((x,x**2) for x in xrange(5)) >>> s (0: 0, 1: 1, 2: 4, 3: 9, 4: 16)

Well, now for practice, let’s try to create a dictionary using a list of tuples:

>>> list = [("name","age"),("Tanya",25)] >>> s = dict(list) >>> s ("Tanya": 25, "name": "age ") >>> len(s) # Dictionary length (number of values) 2

We create a small database and search for ponies:

Code: ludi = ("Ivan": ("phone": "23-44-6", "age": "20"), "Igor": ("phone": "45-2-67", "age " : "40")) name = raw_input("Vvedite imya, chtobi uznat nomer telefona: ") key = "phone" if name in ludi: print "%s phone is %s" % (name, ludi) Result: Vvedite imya, chtobi uznat nomer telefona: Igor Igor phone is 45-2-67

Copying a dictionary using the method copy() :

>>> x = ("name":"admin","room":) >>> y = x.copy() >>> y ("name": "admin", "room": )

But the copy() method only shows the contents of the source. For example, if we remove a value from the 'room' list in x, we see that it is also missing in y:

>>> x["room"].remove(1) >>> y ("name": "admin", "room": )

To prevent this from happening, we use deepcopy():

>>> from copy import deepcopy >>> y = x.deepcopy()

Method get()- Displays the value by key, and if absent, gives None:

>>> a = ("name":"Vitaliy") >>> print a.get("name") Vitaliy

Method items()- returns the entire list of dictionary values:

Code: d = ("name":"user","room":"125") for key, value in d.items(): print(key, value) Result: ("name", "user") ( "room", "125")

Method iteriyems()- returns an iterator - produces the same result:

Code: for k, v in d.iteritems(): print k, v Result: name user room 125

Method keys()- returns a list of keys.

>>> print d.keys() ["name", "room"]

Method pop()- retrieves a value by key and then deletes it:

>>> d.pop("name") "user" >>> d ("room": "125")

Method popitem()- extracts an arbitrary value and then deletes it.

Method update()- changes the dictionary value by key:

>>> d1 = ("room":"12") >>> d.update(d1) >>> d ("room": "12")

Method values()- returns a list of values:

>>> d.values() ["12"]

Operator del- deletes a key: value pair by key:

>>> del d["room"] >>> d()

Views: 3,890

Content Series:

After lists, a dictionary is the most flexible built-in type. If a list is an ordered collection, then a dictionary is an unordered one. Main features of dictionaries:

  1. Access is by key, not by index. Similar to a list, in a dictionary you can access elements in a loop based on keys.
  2. Dictionary values ​​are stored in unsorted order; furthermore, keys may not be stored in the order in which they are added.
  3. Similar to lists, a dictionary can store nested dictionaries. A dictionary can store objects of any type (heterogeneous) as values. The key in the dictionary is an immutable type, which can be a string, an integer, a float, or a tuple consisting of the specified types.
  4. Dictionaries are implemented as hash tables with fast access.
  5. Dictionaries, like lists, store references to objects, not the objects themselves.

Today we will cover the following topics.

  1. What is a dictionary?
  2. Dictionary functions/methods.
  3. Operations with a dictionary.
  4. Examples.

1. What is a dictionary

Dictionary is associative array or hash. It is an unordered set of key:value pairs with the requirement that the keys be unique. A pair of curly braces () creates an empty dictionary. Unlike sequences, dictionary elements are accessed by key, not by index; the key can be of any type; the key cannot be changed.

The main operations on a dictionary are storing with a given key and retrieving a value from it. You can also remove a key: value pair using the del statement.

The keys() method for a dictionary returns a list of all used keys in no particular order; To sort the list you need to use the sort() method. To determine the presence of a certain key, there is a has_key() method, which will become obsolete in version 3.0 - instead there is an in operator. Adding a new object to the dictionary does not require preliminary checks: If the key already had a value associated with it, it will be overwritten.

Example - dictionary as telephone directory:

>>> dic = ("vanya" : 23323223, "smith" : 32232332) >>> dic["fedya"] = 33332222 >>> dic ("vanya": 23323223, "fedya": 33332222, "smith": 32232332) >>> dic["smith"] 32232332 >>> del dic["vanya"] >>> dic ("fedya": 33332222, "smith": 32232332) >>> dic.keys() ["fedya ", "smith"] >>> dic.has_key("fedya") True

You can create a dictionary in several ways:

  1. A common expression - it is convenient if the dictionary is static: D = ("name": "mel", "age": 45)
  2. Dynamic option for creating on the fly: D = () D["name"] = "mel" D["age"] = 45
  3. Using the dict() function, the keys must be strings. With this function you can save yourself from mandatory condition enclose the key in quotes. The example shows four options for creating the same dictionary: d1 = dict(id=1948, name="Washer", size=3) d2 = dict(("id": 1948, "name": "Washer", "size": 3)) d3 = dict([( "id", 1948), ("name", "Washer"), ("size", 3)]) d4 = dict(zip(("id", "name", "size"), (1948, " Washer", 3)))
  4. Using fromkeys() - creates a dictionary using a list of keys with empty values: D = ().fromkeys(["name", "age"],123)
  5. Using the constructor: d = dict((x, x**2) for x in xrange(5))

2. Dictionary functions/methods

dict() - creating a dictionary;

len() - returns the number of pairs;

clear() - removes all values ​​from the dictionary;

copy() - creates a pseudo-copy of the dictionary;

deepcopy() - creates a full copy of the dictionary;

fromkeys() - creating a dictionary;

get() - get the value by key;

has_key() - checking the value by key;

items() - returns a list of values;

iteriyems() - returns an iterator;

iterkeys() - returns a key iterator;

pop() - retrieves a value by key;

popitem() - retrieves an arbitrary value;

update() - changes the dictionary;

values() - returns a list of values;

itervalues() - returns an iterator on a list of values.

in - operator, checks the presence of a value by key;

del - operator, deletes a pair by key;

dict() - constructs a dictionary using a sequence.

For example, create a dictionary using a list of tuples:

>>> items = [("name","sveta"),("age",20)] >>> d = dict(items) >>> d ("age": 20, "name": "sveta ") >>> len(d) 2

in() - occurrence checking operator.

Example: the database can be populated as a dictionary.

Check for a phone number in the database by name:

people = ("Alice": ("phone": "2341", "addr": "Foo drive 23"), "Beth": ("phone": "9102", "addr": "Bar street 42") ) name = "Alice" key = "phone" if name in people: print "%s phone is %s" % (name, people) >>> Alice phone is 2341 copy()

An example of creating a copy of a dictionary:

>>> x = ("user":"admin","attr":) >>> y = x.copy() >>> y ("user": "admin", "attr": )

The copy() method doesn't do full copy: if we, for example, perform the operation:

>>> x["attr"].remove(1)

then we will be surprised to discover that the attribute will also be deleted in the copy.

To prevent this from happening, you need to use the deepcopy() method.

>>> from copy import deepcopy >>> y = x.deepcopy()

fromkeys() - creates a dictionary for the given keys with empty values:

>>> ().fromkeys(["name", "age"]) ("age": None, "name": None)

You can fill in all values ​​by default:

>>> ().fromkeys(["name", "age"],123) ("age": 123, "name": 123)

get() - gets the value by key, if absent, gives None:

>>> d = () >>> print d.get("name") None

has_key() - checks whether the dictionary contains a value for a given key:

>>> d = () >>> d.has_key("name") False

items() - returns a list of values:

for key, value in d.items(): print(key, value)

iteriyems() - returns an iterator - produces the same result:

>>> for k, v in d.iteritems(): ... print k, v

keys() - returns a list of keys;

iterkeys() - returns a key iterator:

>>> d.keys() ["url", "title"] >>> d.iterkeys()

pop() - retrieves a value by key and then deletes it:

>>> d.pop("title") >>> d ("url": "http://www.python.org")

popitem() - retrieves an arbitrary value and then deletes it:

>>> d = ("title": "Python Web Site", "url": "http://www.python.org", "www": "python") >>> d.popitem() >> > d ("www": "python", "title": "Python Web Site")

update() - changes the value by key:

>>> d2 = ("www":"python.org") >>> d.update(d2) >>> d ("www": "python.org", "title": "Python Web Site")

values() - returns a list of values:

>>> d=() >>> d=1 >>> d=2 >>> d=3 >>> d (1: 1, 2: 2, 3: 3) >>> d.values()

del - operator deletes key: value pair by key:

>>> del d >>> d (1: 1, 3: 3)

3. Operations

Because dictionaries are maps and not sequences, they cannot be concatenated or sliced.

Can be applied to dictionaries standard operators comparisons:

<, <=, ==, !=, >=, >

In order to pass through the dictionary keys, we use for:

>>> table = ("Python": "Guido van Rossum", ... "Perl": "Larry Wall", ... "Tcl": "John Ousterhout" ) >>> for lang in table: .. . print(lang, table) .. >>> Tcl John Ousterhout >>> Python Guido van Rossum >>> Perl Larry Wall

Dictionaries are good for storing multidimensional arrays or matrices:

>>> Matrix = () >>> Matrix[(2, 3, 4)] = 88 >>> Matrix[(7, 8, 9)] = 99 >>> >>> X = 2; Y = 3; Z = 4 >>> Matrix[(X, Y, Z)] 88 >>> Matrix ((2, 3, 4): 88, (7, 8, 9): 99)

Using dictionaries, you can store structured information in the form of records:

>>> man = ("name": "Serg", ... "jobs": ["programmer", "writer"], ... "web": "www.iakovlev.org", ... " home": ("city": "Moscow", "zip":129000)) >>> man["name"] Serg >>> man["jobs"] "writer"

4. Examples

Example 1. Let's count how many times each character appears in a line:

def histogram(s): d = dict() for c in s: if c not in d:d[c] = 1 else:d[c] += 1 return d hist = histogram("how many times") > >> ("a": 1,"e": 1,"i": 1,"h": 1,"m": 2,"o": 1,"n": 1,"s": 1 ,"t": 1,"w": 1,"y": 1)

If we need to invert this dictionary and set frequency as the key:

def invert_dict(d): inv = dict() for key in d: val = d if val not in inv:inv = else:inv.append(key) return inv print invert_dict(hist) >>> (1: [" a", "e", "i", "h", "o", "n", "s", "t", "w", "y"], 2: [" ", "m"] )import string import sys words = () strip = string.whitespace + string.punctuation + string.digits + "\""" filename = "file" for line in open(filename): for word in line.lower().split (): word = word.strip(strip) if len(word) > 2: words = words.get(word, 0) + 1 for word in sorted(words): print(""(0)" occurs (1 ) times".format(word, words))

Example 3. Sorting the dictionary by keys:

author = ("php":"Rasmus Lerdorf",\ "perl":"Larry Wall",\ "tcl":"John Ousterhout",\ "awk":"Brian Kernighan",\ "java":"James Gosling ",\ "parrot":"Simon Cozens",\ "python":"Guido van Rossum") #Or like this: langs = author.keys() langs.sort() for language in langs: print language," - " ,author #or this: for key in sorted(author.iterkeys()): print "%s: %s" % (key, author) >>> awk - Brian Kernighan >>> java - James Gosling >>> parrot - Simon Cozens >>> perl - Larry Wall >>> php - Rasmus Lerdorf >>> python - Guido van Rossum >>> tcl - John Ousterhout

Example 4. How to invert a dictionary, i.e. change keys with values:

def invert_dict_nonunique(d): newdict = () for k, v in d.iteritems(): newdict.setdefault(v, ).append(k) return newdict d = ("child1": "parent1","child2": "parent1","child3": "parent2","child4": "parent2") print invert_dict_nonunique(d) >>> ("parent2": ["child3", "child4"], "parent1": ["child1 ", "child2"])

Conclusion

We can summarize: dictionaries, along with lists, are the simplest, most flexible and powerful collection types. A dictionary, like a list, is a mutable data type, although it contains immutable keys and can grow indefinitely. If you need a collection with access by key, a dictionary is best suited for this. If you need a collection to store arbitrary objects of arbitrary nesting, a dictionary will help you with this.

The example code was tested on Python version 2.6.

Resources for download

static.content.url=http://www.site/developerworks/js/artrating/

Zone=Open source, Linux

ArticleID=505647

ArticleTitle=Python Programming: Part 4: Dictionaries

Dictionary in language Python programming called an unordered data set arbitrary type with key access. The elements of such a collection are pairs of objects, each of which includes a key and a value. To work with dictionaries, functions are available that change their contents and perform various operations above them. It can be converted to other data types, such as a string.

Creation

Before you start working with a dictionary, you need to create it. This can be done basic means language by assigning an arbitrary number of pairs of objects to a free variable. Elements must be enclosed in curly braces, and there must be a colon between the key and value. The following example demonstrates the creation of a dictionary named a that includes keys as numbers and values ​​as strings.

A = (1: "one", 2: "two", 3: "three") print(a) (1: "one", 2: "two", 3: "three")

You can display the contents of the dictionary standard function print, specifying it as an argument the right set data. The dict method is also used to populate the dictionary, receiving an arbitrary number of key-value pairs. In this case, only a string can be the key, as shown in the following code example.

A = dict(one = 1, two = 2, three = 3) print(a) ("one": 1, "two": 2, "three": 3)

Just like last time, the print function displays the contents of dictionary a. IN in this case There are pairs of objects, also represented as numbers and strings.

Adding an element

In Python 3, the contents of a dictionary can be changed at any time to suit your needs. For example, in order to add a new pair of objects to the collection, you just need to specify new key in square brackets, as well as its corresponding value.

A = (1: "one", 2: "two", 3: "three") a = "four" print(a) (1: "one", 2: "two", 3: "three", 4 : "four")

The code above uses an assignment operator to place the new pair (4: “four”) at the end of the previously created collection a.

Merging dictionaries

If there is a need to move data from one dictionary to another, you should use the update merge function. You need to call it on an object that is supposed to be expanded with new key and value pairs. Here is an example of how to add a dictionary to a dictionary in Python:

A = (1: "one", 2: "two", 3: "three") b = (4: "four", 5: "five") a.update(b) print(a) (1: " one", 2: "two", 3: "three", 4: "four", 5: "five")

The result of the print method is to display the updated contents of the dictionary called a.

After merging, the new elements were automatically written to the end of the collection.

Removing an element

If the dictionary contains unnecessary information, you can easily get rid of it using the special operation del. To execute it, you must specify the name of the collection, as well as the key in square brackets. The following example shows the removal of a pair.

A = (1: "one", 2: "two", 3: "three") del a print(a) (1: "one", 2: "two")

Since the operation received the key 3, as a result of its operation the value three was also deleted.

Getting the size

Function len allows you to determine the current number of dictionary elements at any time, if you pass it the name of the collection as an argument. In the example below, the print method prints the dimension of the dictionary a.

A = (1: "one", 2: "two", 3: "three") print(len(a)) 3

It is worth noting that the len function returns the exact number of pairs, but not objects. In this case, there is a dictionary that contains exactly 3 pairs.

Dictionary search

You can enumerate the elements of a dictionary in several ways, depending on the information you want to obtain about its contents.

Iteration of elements can be carried out in order to obtain for subsequent processing:

  • Key-value pairs;
  • Enumeration of all keys;
  • Iterating over values.

This example shows how to display all pairs of this collection in the format key: value. To do this, we use a for loop and the items function, which works with dictionary elements.

A = (1: "one", 2: "two", 3: "three") for key, value in a.items(): print(key, ":", value) 1: one 2: two 3: three

To get only the keys, use the keys method by calling it on the dictionary.

A = (1: "one", 2: "two", 3: "three") for key in a.keys(): print(key) 1 2 3

You need to do the same thing to display only the dictionary values. However, in this case, in for loop The values ​​method is used.

A = (1: "one", 2: "two", 3: "three") for val in a.values(): print(val) one two three

In both cases, only the selected part of the pair, the key or value, is displayed.

Search

You can check the presence of a specific key using the in operation. To do this, it is enough to display the result of its execution for a dictionary named a.

A = (1: "one", 2: "two", 3: "three") print(2 in a) print(4 in a) True False

As you can see, checking key 2 gave a positive result (True). In the second case, the value was False because key 4 was not found in the dictionary.

Sorting

Language tools make it possible to sort a dictionary in Python by keys and values, depending on the need. The following example has a data collection named a that contains information in no particular order. The keys here are numbers, and the values ​​are strings. Sorting is carried out using the imported operator module and the built-in itemgetter method receiving 0 or 1.

Import operator a = (2: "two", 3: "three", 1: "one") b = sorted(a.items(), key = operator.itemgetter(0)) print(b) b = sorted( a.items(), key = operator.itemgetter(1)) print(b) [(1, "one"), (2, "two"), (3, "three")] [(1, "one" "), (3, "three"), (2, "two")]

As you can see, argument 0 allows you to sort the dictionary by key, while 1 allows you to display its contents in alphabetical order values.

Comparison

Sometimes you need to make sure that two dictionaries contain exactly the same data, or find out which collection is larger or smaller in size. In this case, the cmp method comes to the rescue, receiving two dictionaries as parameters.

A = (1: "one", 2: "two", 3: "three") b = (4: "four", 5: "five") c = (1: "one", 2: "two" , 3: "three") print(cmp(a, b)) print(cmp(b, c)) print(cmp(a, c)) 1 -1 0

The following code demonstrated the execution of the cmp method with three combinations of arguments. As can be seen from the output results, the function returns 1 if the first is greater than the second, -1 if vice versa and 0 when the data is completely identical.

Copy

The copy method is used to copy the contents of one dictionary to another. This example demonstrates transferring keys and values ​​from collection a to b.

A = (1: "one", 2: "two", 3: "three") b = a.copy() print(b) (1: "one", 2: "two", 3: "three" )

As you can see, the order and contents of all pairs have been preserved in the new set.

Cleaning

To get rid of all elements of a dictionary, you should call the clear function on it.

A = (1: "one", 2: "two", 3: "three") a.clear() print(a) ()

The result is a completely empty data set.

Dictionary generator

As with other data sets, You can fill dictionaries using. The following example demonstrates the creation of numeric collection pairs using the Python dictionary generator with the range method taking 5 as an argument.

A = (a: a * a for a in range(5)) print(a) (0: 0, 1: 1, 2: 4, 3: 9, 4: 16)

Thus, the output is a dictionary a, which includes exactly 5 pairs. The keys are numbers from 0 to 4, and the values ​​are their mathematical squares.

Convert to string

A dictionary can be very easily converted to a string for more comfortable work with a complete presentation of its contents. To do this you will need the function str. As you can see from the results of the type method, the conversion was successful.

A = (1: "one", 2: "two", 3: "three") b = str(a) print(b) print(type(b)) (1: "one", 2: "two" , 3: "three")

Converting a Python string to a dictionary works in a similar way.. It is important that its text content matches the structure of the collection in question.

A = "(1: "one", 2: "two", 3: "three")" b = eval(a) print(b) print(type(b)) (1: "one", 2: " two", 3: "three")

As you can see from the example, the eval method converts the entire text of the string into a new dictionary.

Nested

In Python, dictionaries can be nested, that is, they can be part of another larger dictionary.. Using the familiar curly braces and colons, you can delineate the boundaries of this data set and provide the program with key-value pairs.

A = ( "First": ( 1: "one", 2: "two", 3: "three" ), "Second": ( 4: "four", 5: "five" ) ) print(a) ( "First": (1: "one", 2: "two", 3: "three"), "Second": (4: "four", 5: "five"))

In the example described above, a dictionary a is created that includes two other dictionaries (First and Second). Those, in turn, contain several pairs of keys and values.

Summary

The following table demonstrates a brief summary of all the methods discussed for working with dictionaries in Python 3. The table displays the names of the methods, as well as information about their purpose.

A dictionary is an unordered data structure that allows you to store key-value pairs. Here is an example dictionary in Python:

Dictionary = ("person": "person", "marathon": "a race of runners about 26 miles long", "confront": "stay strong despite pressure", "run": "move at speed")

This dictionary uses strings as keys, but a key can in principle be any immutable data type. The value of a specific key can be anything. Here is another example of a dictionary where the keys are numbers and the values ​​are strings:

Gender_dict = (0: "husband", 1: "female")

Important clarification: if you try to use a mutable data type as a key, you will receive an error:

Dictionary = ((1, 2.0): "tuples can be keys", 1: "integers can be keys", "run": "strings too", ["sock", 1, 2.0]: "but lists cannot ")

Note translation Actually the problem is not with mutable data types, but with non-hashable data types, but usually they are the same thing.

Retrieving Data from a Dictionary

Square brackets are used to obtain the value of a specific key. Let's assume that in our dictionary there is a pair "marathon": 26.

# take the value with the key "marathon" dictionary["marathon"]

Again, you will get an error if you try to get a value from a non-existent key. To avoid such mistakes, there are methods that we will talk about now.

Adding and updating keys

Adding new pairs to the dictionary is quite simple:

# Add the key "shoe" with the value "a type of shoe that covers the leg no higher than the ankle" dictionary["shoe"] = "a type of shoe that covers the leg no higher than the ankle"

Updating existing values ​​occurs in exactly the same way:

# Update the key "shoe" and assign it the value "good shoe" dictionary["shoe"] = "good shoe"

Removing keys

To remove a key and corresponding value from a dictionary you can use del

# Remove the value with the key "resist" from the dictionary del dictionary["resist"]

Methods

Dictionaries in Python have many different useful methods to help you work with them. Here are just a few of them:

Update

The update() method is useful if you need to update several pairs at once. The method takes another dictionary as an argument.

# Add two pairs to the dictionary using the update method dictionary.update(("ran": "run in the past tense", "shoes": "plural shoe")) >>> dictionary ("marathon": "race" runners about 26 miles long", "person": "a person", "ran": "to run in the past tense", "run": "to move at speed", "shoe": "a type of shoe that covers the foot no higher than the ankle" , "shoes": "plural shoe")

If you are wondering why the data in a dictionary is not in the order in which it was entered, it is because dictionaries are not ordered.

Get

# Let's say we have a dictionary story_count story_count = ("one hundred": 100, "ninety": 90, "twelve": 12, "five": 5)

The get() method returns the value for the specified key. If the specified key does not exist, the method will return None .

# Key "twelve" exists and get method in this case it will return 12 story_count.get("twelve")

The method can be used to check for the presence of keys in a dictionary:

>>> story_count.get("two") None

You can also specify a default value that will be returned instead of None if the key is not in the dictionary:

# The method will return 0 if given key does not exist story_count.get("two", 0)

Pop

pop method() removes a key and returns its corresponding value.

>>> story_count.pop("ninety") 90 >>> story_count ("twelve": 12, "one hundred": 100, "five": 5)

Keys

The keys() method returns a collection of keys in a dictionary.

>>> story_count.keys() ["one hundred", "five", "twelve"]

Values

The values() method returns a collection of values ​​in a dictionary.

>>> story_count.values()

Items

The items() method returns key-value pairs.

>>> dictionary.items() [("person", "person"), ("run", "move at speed"), ("shoe", "a type of shoe that covers the foot no higher than the ankle"), (" ran", "run in the past tense"), ("marathon", "a race of runners about 26 miles long"), ("shoes", "plural shoe")]

Iterate through a dictionary

You can iterate over each key in the dictionary.