- Распаковать словарь словарей python
- Деструктуризация в циклах
- Игнорирование значений
- Упаковка значений и оператор *
- Распаковка и операторы * и **
- How to Unpack Dictionary in Python
- Dictionaries in Python
- How to Unpack Dictionary in Python
- Using the Unpack Operator ( ** ) to Unpack Dictionary in Python
- Further reading:
- Using the for Loop to Unpack Dictionary in Python
- Using the iteritems() Function to Unpack Dictionary in Python
- Using the items() Function to Unpack Dictionary in Python
- Using the keys and values Functions to Unpack Dictionary in Python
- Conclusion
Распаковать словарь словарей python
Распаковка ( unpacking , также называемая Деструктуризация ) представляет разложение коллекции (кортежа, списка и т.д.) на отдельные значения.
Так, как и многие языки программирования, Python поддерживает концепцию множественного присваивания. Например:
x, y = 1, 2 print(x) # 1 print(y) # 2
В данном случае присваивем значения сразу двум переменным. Присвоение идет по позиции: переменная x получает значение 1, а переменная y — значени 2.
Данный пример в действительности уже представляет деструктуризацию или распаковку. Значения 1, 2 фактически являются кортежом, поскольку именно запятые между значениями говорят о том, что это кортеж. И мы также могли бы написать следующим образом:
x, y = (1, 2) print(x) # 1 print(y) # 2
В любом случае мы имеем дело с деструктуризацией, когда первый элемент кортежа передается первой переменной, второй элемент — второй переменной и так далее. То есть разложение идет по позиции.
Подобным образом можно разложить другие кортежи, например:
name, age, company = ("Tom", 38, "Google") print(name) # Tom print(age) # 38 print(company) # Google
Только кортежами мы не ограничены и можем «распаковывать» и другие коллекции, например, списки:
people = ["Tom", "Bob", "Sam"] first, second, third = people print(first) # Tom print(second) # Bob print(third) # Sam
При разложении словаря переменные получают ключи словаря:
dictionary = r, b, g = dictionary print(r) # red print(b) # blue print(g) # green # получаем значение по ключу print(dictionary[g]) # зеленый
Деструктуризация в циклах
Циклы в Python позволяют разложить коллекции на отдельные составляющие:
people = [ ("Tom", 38, "Google"), ("Bob", 42, "Microsoft"), ("Sam", 29, "JetBrains") ] for name, age, company in people: print(f"Name: , Age: , Company: ")
Здесь мы перебираем список кортежей people. Каждый кортеж состоит из трех элементов, соответственно при переборе мы можем их передать в переменные name, age и company.
Другой пример — функция enumerate() . Она принимает в качестве параметра коллекцию, создает для каждого элемента кортеж и возвращает набор из подобных кортежей. Каждый кортеж содержит индекс, который увеличивается с каждой итерацией:
people = ["Tom", "Bob", "Sam"] for index, name in enumerate(people): print(f".") # результат # 0.Tom # 1.Bob # 2.Sam
Игнорирование значений
Если какой-то элемент коллекции не нужен, то обычно для него определяется переменная с именем _ (прочерк):
person =("Tom", 38, "Google") name, _, company = person print(name) # Tom print(company) # Google
Здесь нам не важен второй элемент кортежа, поэтому для него определяем переменную _. Хотя в реальности _ — такое же действительное имя, как name и company:
name, _, company = person print(_) # 38
Упаковка значений и оператор *
Оператор * упаковывает значение в коллекцию. Например:
num1=1 num2=2 num3=3 *numbers,=num1,num2,num3 print(numbers) #[1, 2, 3]
Здесь мы упаковываем значения из кортежа (num1,num2,num3) в список numbers. Причем, чтобы получить список, после numbers указывается запятая.
Как правило, упаковка применяется для сбора значений, которые остались после присвоения результатов деструктуризации. Например:
head, *tail = [1, 2, 3, 4, 5] print(head) # 1 print(tail) # [2, 3, 4, 5]
Здесь переменная head в соответствии с позицией получае первый элемент списка. Все остальные элементы передаются в переменную tail . Таким образом, переменная tail будет представлять список из оставшихся элементов.
Аналогичным образом можно получить все кроме последнего:
*head, tail = [1, 2, 3, 4, 5] print(head) # [1, 2, 3, 4] print(tail) # 5
Или элементы по середине, кроме первого и последнего:
head, *middle, tail = [1, 2, 3, 4, 5] print(head) # 1 print(middle) # [2, 3, 4] print(tail) # 5
Или все кроме первого и второго:
first, second, *other = [1, 2, 3, 4, 5] print(first) # 1 print(second) # 2 print(other) # [3, 4, 5]
Вообщем, таким образом мы можем получать различные комбинации элементов коллекции. Причем не только списков, но и кортежей, словарей и других коллекций.
Другой пример — нам надо получить только первый, третий и последний элемент, а остальные элементы нам не нужны. В общем случае мы должны предоставить переменные для всех элементов коллекции. Однако если коллекция имеет 100 элементов, а нам нужно только три, не будем же мы определять все сто переменных. И в этом случае опять же можно применить упаковку:
first, _, third, *_, last = [1, 2, 3, 4, 5, 6, 7, 8] print(first) # 1 print(third) # 3 print(last) # 8
Также можно получить ключи словаря:
red, *other, green = print(red) # red print(green) # green print(other) # ['blue', 'yellow']
Распаковка и операторы * и **
Оператор * вместе с оператором ** также может применяться для распаковки значений. Оператор * используется для распаковки кортежей, списков, строк, множеств, а оператор ** — для распаковки словарей. Особенно это может быть полезно, когда на основе одних коллекций создаются другие. Например, распаковка кортежей и списков:
nums1 = [1, 2, 3] nums2 = (4, 5, 6) # распаковываем список nums1 и кортеж nums2 nums3 = [*nums1, *nums2] print(nums3) # [1, 2, 3, 4, 5, 6]
Здесь распаковывем значения из списка nums1 и кортежа nums2 и помещаем их в список nums3.
Подобным образом раскладываются словари, только применяется оператор ** :
dictionary1 = dictionary2 = # распаковываем словари dictionary3 = <**dictionary1, **dictionary2>print(dictionary3) #
How to Unpack Dictionary in Python
In this article, we will see how to unpack dictionary in Python.
Dictionaries in Python
A dictionary is one of the fundamental data structures of Python. It stores its elements as key-value pairs and has evolved with time. In recent versions of Python, dictionaries use hash functions which make accessing values from keys a fast process and are also known to retain the order of elements.
Python uses the dict class that represents dictionaries as the base for many other objects so many operations are possible with them. We can unpack dictionaries as well.
Unpacking a dictionary means unloading and printing the key-value pairs or loading them in other objects like a tuple or a list. We also unpack a dictionary while sending their values to a function or when we are merging two dictionaries.
For this, we have the unpack operator in Python and loads of various functions that can be utilized.
How to Unpack Dictionary in Python
We will now discuss different ways how to unpack dictionary in Python.
Using the Unpack Operator ( ** ) to Unpack Dictionary in Python
The ** operator is used to pack and unpack dictionary in Python and is useful for sending them to a function. This will be made more clear with an example.
In the above example, we have a function that accepts three arguments. We pass these three arguments by packing them in a dictionary using the ** operator.
We can use the ** to unpack dictionaries and merge them in a new dict object.
In the above example, we create a new dictionary by unpacking the contents of the previous dictionary in the new dictionary.
We also have an operator to unpack elements from the list. We can use this operator for dictionaries after converting them to a list of key-value pairs. We will discuss the methods to convert a dictionary to a list of key-value pairs as tuples below and unpack the elements using this operator.
Further reading:
Check if key exists in Dictionary
List of Dictionaries in Python
Using the for Loop to Unpack Dictionary in Python
Dictionaries are iterable in Python. We can use the for loop to iterate by a dictionary and print its contents.
While iterating through a dictionary, we use its keys. We will then use the keys to access the value at every iteration and display them both.
See the following example.
In every iteration, we use the k variable to access the value at the given iteration and display them both.
We can also append them to a list of tuples. For this, we will create an empty list and append the key-value pairs as a tuple in every iteration.
In the above example, we first created an empty list lst and then went on to append the key-value pairs as a tuple using the append() function.
After creating the list, we can unpack the elements using the unpack operator( * ) operator discussed previously.
Using the iteritems() Function to Unpack Dictionary in Python
The iteritems() function was available in Python 2 and it would return the key-value pairs of the dictionary in a view object.
We can use it to unpack dictionary in Python.
This function was replaced by the items() function in Python 3.
Using the items() Function to Unpack Dictionary in Python
The items() function replaced the iteritems() function in Python 3 and returns a better view object of the dictionary backed by the dict class. This function returns an object of type dict_items .
We can use the unpack operator ( * ) for lists with this object.
In the above example, we can observe the type of object returned by the items() function is similar to a list but is backed by the dict class.
This function is also available in Python 2. However, in Python 2, this method directly returns a list of the elements of the dictionary and not a view-object. Any changes made in the dictionary after the items() function call will not be observed in the returned list in Python 2.
Using the keys and values Functions to Unpack Dictionary in Python
The keys() and values() function of the dict class return a view-like object of the keys and values of a dictionary respectively.
We can use these functions with the zip() method to unpack dictionary in Python.
- The zip() method combines the corresponding elements at each position in the view objects.
- This object is converted to a list using the list() function.
- Elements are unpacked from this list using the unpack operator.
Conclusion
To conclude, in this article we discussed dictionaries and how to unpack dictionary in Python. We started by discussing dictionaries and unpack operations in Python. We can use the unpack operators with dictionaries in Python. The ** is directly used for packing and sending a dictionary as a function argument. We can also use this to unpack and merge dictionaries. We also have the unpack operator ( * ) operator that can unpack elements from lists or tuples. To use this, we convert the dictionary to a list of tuples and unpack the elements from this list. Several functions can be used to convert a dictionary to a list and then unpack them.
That’s all about how to unpack dictionary in Python.