官术网_书友最值得收藏!

Dictionary Methods

Now that you have learned about dictionaries and when you should use a dictionary. You will now look at a few other dictionary methods. To start with, you should follow the exercises from here onward to learn how to access the values and other related operations of a dictionary in Python.

Exercise 30: Accessing a Dictionary Using Dictionary Methods

In this exercise, we will learn how to access a dictionary using dictionary methods. The goal of the exercise is to print the order values against the item while accessing the dictionary by using dictionary methods:

  1. Open a new Jupyter Notebook.
  2. Enter the following code in a new cell:

    orders = {'apple':5, 'orange':3, 'banana':2}

    print(orders.values())

    print(list(orders.values()))

    You should get the following output:

    dict_values([5, 3, 2])

    [5, 3, 2]

    The values() method in this code returns an iterable object. In order to use the values straight away, you can wrap them in a list directly.

  3. Now, obtain a list of keys in a dictionary by using the keys() method:

    print(list(orders.keys()))

    You should get the following output:

    ['apple', 'orange', 'banana']

  4. As you can't directly iterate a dictionary, you first convert it to a list of tuples using the items() method, then iterate the resulting list and access it. This is mentioned in the following code snippet:

    for tuple in list(orders.items()):

      print(tuple)

    You should get the following output:

    ('apple', 5)

    ('orange', 3)

    ('banana', 2)

In this exercise, you created a dictionary. In addition to this, you were able to list the keys mentioned in the dictionary, and later, in step 4, you were able to iterate the dictionary after converting the list to a tuple.

主站蜘蛛池模板: 珲春市| 锡林郭勒盟| 丘北县| 灌云县| 新余市| 资源县| 和田县| 三原县| 车致| 杨浦区| 余江县| 耒阳市| 济阳县| 固镇县| 伊金霍洛旗| 桓台县| 宿迁市| 青阳县| 陇川县| 洱源县| 安龙县| 常宁市| 阜平县| 得荣县| 海伦市| 天全县| 连城县| 台南市| 泰安市| 育儿| 福建省| 昌宁县| 南通市| 石狮市| 弥勒县| 镶黄旗| 苍山县| 桓仁| 五大连池市| 色达县| 富源县|