RUVIDEO
Поделитесь видео 🙏

How to Create Dictionary in python and how to access data from dictionary through for loop items()

Python Dictionary

Python Dictionaries are collections of elements in the form of a key:value pairs
Or
Dictionaries are containers that stores data/information in the form of a
Key:value pairs.

Syntax of Dictionary:-
Dictionary_name = { "Key" : "value" , "Key" : "Value"}
So let’s start with some example
Employee
Name Department
Deepak (key) Accounts (Value)
Satender (key) Accounts (Value)
Anil (key) Sales(Value)
Bindiya (key) HR (Value)

employee={"Deepak" : "Accounts",\
"Satender":"Accounts",\
"Anil" : " Sales",\
"Bindiya" : "HR" }
How to access values of keys in Dictionary
As we know that dictionary is a one way key mapping
Form key to value
Key value
Means with the help of key you can find the data/ information.
1. To access whole data in a default way
{'Deepak': 'Accounts', 'Satender': 'Accounts', 'Anil': ' Sales', 'Bindiya': 'HR'}
2. To access individual data of each key
Accounts
Accounts
Sales
HR
3. To access whole data with the help of for loop ( Sequence of key, value pairs )
Name Department
Deepak Accounts
Satender Accounts
Anil Sales
Bindiya HR
4. To access whole data with the help of items() method of dictionary
Sequence of key, value pairs
Deepak Accounts
Satender Accounts
Anil Sales
Bindiya HR
To access whole data in a default way
{'Deepak': 'Accounts', 'Satender': 'Accounts', 'Anil': ' Sales', 'Bindiya': 'HR'}
print(employee) (code to print whole data in a default way)
out put
{'Deepak': 'Accounts', 'Satender': 'Accounts', 'Anil': ' Sales', 'Bindiya': 'HR'}

To access individual data of each key
Accounts
Accounts
Sales
HR
Let suppose if you want to print value of satender key then code could be like this
print(employee[‘Satender’])
thus if you want to search or print data/information of particular key,
you have to pass key name (instead of providing index number as in the case of list) as a parameter.
Syntax is print(dictionary_name[‘key’])
print(employee['Deepak'])
print(employee['Satender']) To access individual data of each key
print(employee['Anil'])
print(employee['Bindiya'])
3. To access whole data with the help of for loop ( Sequence of key, value pairs )
Name Department
Deepak Accounts
Satender Accounts
Anil Sales
Bindiya HR
for x in employee: here x is a variable that store key of dictionary employee
print(x,' ',employee[x]) first time x will hold Deepak
next time x will hold Satender, next time x will hold Anil and next time x will hold Bindiya
hence values of x are Deepak, Satender, Anil, Bindiya
So print(x) will print value of x
and print(employee[x]) will print value of employee[‘Deepak’]) that is Accounts
in the same manner value of Satender is Accounts just like as the case of accessing individual value of each key.
Name Department
Deepak Accounts
Satender Accounts
Anil Sales
Bindiya HR
4. To access whole data with the help of items() method of dictionary
Sequence of key, value pairs
Deepak Accounts
Satender Accounts
Anil Sales
Bindiya HR
for k,v in employee.items():
print(k,' ',v)
In this case we have use items() method of dictionary with the for loop
Items() method returns data in key and value format. So it is mandatory to provide two loop variable to hold key and its value. So I have used k, v variable to hold key and value from employee dictionary.
And pass it to print(k,v) function.
Output is
Deepak Accounts
Satender Accounts
Anil Sales
Bindiya HR


How to update existing element(s) in a Dictionary.
You can update existing element(s) in a dictionary by providing value to
a key (existing key)
Syntax:
Dictionary-name[Existing key]=value
Consider following example
Employee[‘Anil’]=’Purchase’
print(employee)

The above code will change/ update the value of Anil key Sales to Purchase
How to add new key and its value to dictionary
You can add new key and its value by using
Dictionary [new key] =value (just like update entry)
Note:- the key being added must not exist in dictionary and must be unique.
If the key already exists, then this statement will change the value of existing key and no new entry will be added to dictionary.
How to delete element from a Dictionary
There are two methods for deleting elements from a dictionary.
a) del command
del dictionary [key]

del employee["Satender"]
print(employee)

Key ‘Satender’ and its value ‘Accounts’ deleted
b) pop() method
syntax
deictionary.pop(key)
employee.pop("Anil")
print(employee)

Key ‘Anil’ and its value ‘Sales’ deleted

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «How to Create Dictionary in python and how to access data from dictionary through for loop items()», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.