Lecture 19: Dictionaries In Python
Dictionaries In Python:
A dictionary is a collection which is unordered, changeable and indexed.
In Python dictionaries are written with curly brackets, and they have keys and values.
Dictionary in Python is an unordered collection of data values, used to store data values like a map.
Dictionary holds key:value pair.
Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable.
In Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.
Dictionary can be created by the built-in function dict().
An empty dictionary can be created by just placing to curly braces { }.
dict1 = {
"Name": "Amol",
"Age": 37,
"year": 1982
}
print(dict1)
It is also possible to use the dict() constructor to make a new dictionary.
dict1 = dict(brand="Maruti", model="Swift”, year=1998)
print(dict1)
We can access the items of a dictionary by referring to its key name, inside square brackets.
x = dict1['model']
There is also a method called get() that will access the items from a dictionary.
x = dict1.get("model")
Change Values:
We can change the value of a specific item by referring to its key name.
dict1 = {
"Name": "Amol",
"Age": 37,
"year": 1982 }
dict1["year"] = 2005
print(dict1)
Print all key names in the dictionary, one by one.
for x in dict1:
print(x)
Print all values in the dictionary, one by one.
for x in dict1:
print(dict1[x])
We can also use the values() method to return values of a dictionary.
for x in dict1.values():
print(x)
Loop through both keys and values, by using the items() method.
for x, y in dict1.items(): print(x, y)
Adding an item to the dictionary is done by using a new index key and assigning a value to it.
Example:
dict1 = {
"brand": "Maruti",
"model": "Swift",
"year": 1998
}
dict1["color"] = "white"
print(dict1)
The pop() method removes the item with the specified key name.
dict1.pop("model") ; print(dict1)
The popitem() method removes the last inserted item.
dict1.popitem("model"); print(dict1)
The del keyword removes the item with the specified key name.
del dict1["model"]; print(dict1)
The del keyword can also delete the dictionary completely.
del dict1 ; print(dict1)
The clear() method empties the dictionary.
dict1.clear()
print(dict1)
The pop() method removes the item with the specified key name.
dict1.pop("model") ; print(dict1)
The popitem() method removes the last inserted item.
dict1.popitem("model"); print(dict1)
The del keyword removes the item with the specified key name.
del dict1["model"]; print(dict1)
The del keyword can also delete the dictionary completely.
del dict1 ; print(dict1)
The clear() method empties the dictionary.
dict1.clear()
print(dict1)
You cannot copy a dictionary simply by typing dict2 = dict1, because dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.
Make a copy of a dictionary with the copy() method.
dict2 = dict1.copy()
print(dict2)
Another way to make a copy is to use the built-in function dict().
dict2 = dict(dict1)
print(dict2)
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Lecture 19: Dictionaries In Python», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.