CODDY – финалист международной премии #МЫВМЕСТЕ 2022 в номинации «Ответственный бизнес»CODDY is finalist of international award #MyVmeste 2022 in “Responsible business” nomination
Лучший социальный проект года 2022Coddy Donate is participant in the competition of projects in the field of social entrepreneurship "The best social project of the year-2022”
Курсы CODDY сертифицированы в соответствии с европейскими стандартами и аккредитованы HiSTES (High School Teachers European Society)CODDY courses are certified in accordance with European standards and accredited by HiSTES (High School Teachers European Society)
Проект «Бесплатное обучение программированию для детей с особенностями развития и из детских домов» признан лучшим социальным онлайн-проектомThe charity project “Free coding classes for kids with special needs” is recognised as the Best social online project
CODDY – победитель премии GLOBEE® в категории Компания Года I ФраншизаCODDY is GOLD GLOBEE® WINNER in category Company of the Year | Franchise
CODDY - официальный партнер AcerCODDY is official partner of Acer company

Up

26
Oct
26.10.23
What you need to know about dictionaries in Python
In this fascinating article, we'll dive into the world of Python dictionaries and tell you everything you need to know, from the basics to advanced techniques.
What you need to know about dictionaries in Python

What you need to know about dictionaries in Python

In the world of the Python programming language, which is considered one of the most beginner-friendly, there are key data structures that underpin information processing. Today, we invite you into the fascinating world of "dictionaries".

Dictionaries in Python are not just containers for data, they open doors to the amazing possibilities of this language. They simplify the lives of novice programmers and expand the horizons of experienced developers.


Content ▼      


What are dictionaries




Dictionaries in Python are modifiable mappings of references to objects accessible by key. Dictionaries are data structures in which unique keys represent values.

The key and value are separated by a colon, key-value pairs are separated by commas, and the entire dictionary is bounded by curly braces {}.

In simple words, it is something like a phone book, where under each number there is a person.




Only in the language of developers numbers are called keys, and the people they belong to are called values.


For what purposes dictionaries will be useful to us




  • Counting some objects, where the keys are the names of the objects and the object is their number.
  • To save memory if there is an array that does not use all indexes in order.
  • Setting correspondences between objects, sorting.
  • Storing data from different objects (for example: the key is the ID of a VKontakte user, and the object is an array with data).

A key can be an arbitrary unchangeable data type: different numbers, strings, tuples. A key in the dictionary cannot be a set, but it can be an immutable element of frozenset type. 

The value of a dictionary element can be any changeable or immutable data type.


Dictionary creation




Creating a dictionary in Python is formalized by curly braces. Inside them are key-value pairs. The key is written first, followed by the value, followed by a colon.

The pairs themselves are separated from each other by commas.


dict = {
          'Fortnite' : 'Epic Games',
          'Grand Theft Auto V' : 'Rockstar Games'
          }


Ideally, you can not specify any values for the keys at all: the language will automatically substitute None values for them. But the dictionary will still work.


dict = {
          'Fortnite',
          'Grand Theft Auto V'
          }


Let's print the elements of the dictionary using the print function:


print(dict)
          {'Fortnite', 'Grand Theft Auto V'}


Only the keys are shown. Now let's try to print the full dictionary with values:


dict = {
          'Fortnite' : 'Epic Games',
          'Grand Theft Auto V' : 'Rockstar Games'
          }
print(dict)
          {'Fortnite' : 'Epic Games', 'Grand Theft Auto V' : 'Rockstar Games'}


Python dictionary methods




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

copy() - create a copy of the dictionary


dict1 = {
          'car' : 'car',
          'apple' : 'apple',
          'orange' : 'orange'
          }
dict2 = dict1.copy()
print(dict2) #Print {'car' : 'car', 'apple' : 'apple', 'orange' : 'orange'}


get() - get value by key


dict = {
          'car' : 'car',
          'apple' : 'apple',
          'orange' : 'orange'
          }
print(dict.get('car')) #Print 'car'


clear() - clearing the dictionary


dict = {
          'car' : 'car',
          'apple' : 'apple',
          'orange' : 'orange'
          }
dict.clear()
print(dict) #Print {}


keys() - get all the keys of the dictionary


dict = {
          'car' : 'car',
          'apple' : 'apple',
          'orange' : 'orange'
          }
print(dict.keys()) #Print dict_keys(['car', 'apple', 'orange'])


values() - get all the values of the dictionary elements


dict = {
          'car' : 'car',
          'apple' : 'apple',
          'orange' : 'orange'
          }
print(dict.values()) #Print dict_values(['car', 'apple', 'orange'])


items() - get all items in the dictionary, including keys


dict = {
          'car' : 'car',
          'apple' : 'apple',
          'orange' : 'orange'
          }
print(dict.items()) #Print dict_items([('car', 'car'), ('apple', 'apple'), ('orange', 'orange')])


pop() - removes and returns the value of the key


dict = {
          'car' : 'car',
          'apple' : 'apple',
          'orange' : 'orange'
          }
print(dict.pop('car')) #Pop up 'car'
print(dict) #Pop up {'apple' : 'apple', 'orange' : 'orange'}


popitem() - removes and returns the name and value of the key


dict = {
          'car' : 'car',
          'apple' : 'apple',
          'orange' : 'orange'
          }
print(dict.pop()) #Print ('orange', 'orange')
print(dict) #Print {'car' : 'car', 'apple' : 'apple'}


setdefault() - get value by key if such a key is present in the dictionary. When such a key is not present, it is created with the value None (if it is not specified in the properties). Let's look at an example:


dict = {
          'car' : 'car',
          'apple' : 'apple',
          'orange' : 'orange'
          }
print(dict.setdefault('car') #Print 'car'
print(dict.setdefault('home', 'home') #Print 'home'
print(dict) #Print {'car' : 'car', 'apple' : 'apple', 'orange' : 'orange', 'home' : 'house'}


update({}) - update values by key, adding new keys:


dict = {
          'car' : 'car',
          'apple' : 'apple',
          'orange' : 'orange'
          }
dict.update({'car' : 'automobile', 'home' : 'home'})
print(dict) #Print {'car' : 'car', 'apple' : 'apple', 'orange' : 'orange', 'home' : 'house'}


It is better not to memorize bare theory, but to practise what you know right away. You can start, for example, with the free exercises on stepik.org. And to quickly find the right method and not to google every time, you can already start learning in full at the CODDY programming school. Mentors will help you sort out all your mistakes and put all your knowledge on the shelves.


Working with dictionaries




Changing the dictionary

Let's add an object to our dictionary. To do this, we need to come up with a value for the key. Let's look at an example:


dict = {
          'car' : 'car',
          'apple' : 'apple'
          }
dict['orange'] = 'orange' #In square brackets, give the key name and the value after the equals sign
print(dict) #Print {'car' : 'car', 'apple' : 'apple', 'orange' : 'orange'}


To delete a key and its object in the dictionary, use the del method, specifying the name of the key in square brackets:


dict = {
          'car' : 'car',
          'apple' : 'apple',
          'orange' : 'orange'
          }
del dict['orange']
print(dict) #Print {'car' : 'car', 'apple' : 'apple'}


Enumerating dictionary entries in Python

To output all keys and values in order, we use a loop with the in operator:


dict = {
          'car' : 'car',
          'apple' : 'apple',
          'orange' : 'orange'
          }
for key in dict:
print(key, dict[key])
#print:
#car car
#apple apple
#orange orange


To output a value by key, we use the dictionary name and square brackets with the name of the desired key:


dict = {
          'car' : 'car',
          'apple' : 'apple',
          'orange' : 'orange'
          }
print(dict['car']) #Print 'car'


Dictionaries in Python are powerful weapons that can help you with a variety of tasks. Don't be afraid to experiment, create and apply dictionaries to your projects. Remember, knowing this data structure makes you a true magician in the world of Python.

Let's explore and make magic happen with dictionaries!

Sign up for a course
Registration completed successfully!
An error occurred. Please inform the administrator
You have sent many applications. try later
Your name and surname
This field is required
Your phone
+1
  • Russian Federation (Российская Федерация)+7
  • Belarus(Беларусь)+375
  • Afghanistan(افغانستان)+93
  • Åland Islands+358
  • Albania(Shqipëri)+355
  • Algeria(الجزائر)+213
  • American Samoa+1
  • Andorra+376
  • Angola+244
  • Anguilla+1
  • Antarctic+672
  • Antigua and Barbuda+1 (268)
  • Argentina+54
  • Armenia(Հայաստան)+374
  • Australia+61
  • Austria(Österreich)+43
  • Azerbaijan(Azərbaycan)+994
  • Bahamas+1 (242)
  • Bahrain(البحرين)+973
  • Bangladesh(বাংলাদেশ)+880
  • Barbados+1 (246)
  • Belgium(België)+32
  • Belize+501
  • Benin(Bénin)+229
  • Bolivia+591
  • Bosnia and Herzegovina+387
  • Botswana+267
  • Brazil+55
  • Brunei+673
  • Bulgaria(България)+359
  • Burkina Faso+226
  • Burundi(Uburundi)+257
  • Cambodia(កម្ពុជា)+855
  • Cameroon(Cameroun)+237
  • Canada+1
  • Cape Verde(Kabu Verdi)+238
  • Central African Republic+236
  • Chad(Tchad)+235
  • Chile+56
  • China(中国)+86
  • Colombia+57
  • Comoros(جزر القمر)+269
  • Cook Islands+682
  • Costa Rica+506
  • Croatia(Hrvatska)+385
  • Cuba+53
  • Cyprus(Κύπρος)+357
  • Czech(Česká republika)+420
  • Denmark(Danmark)+45
  • Djibouti+253
  • Dominica+1 (767)
  • Dominican Republic(República Dominicana)+1
  • DR Congo+243
  • Ecuador+593
  • Egypt(مصر))+20
  • Equatorial Guinea(Guinea Ecuatorial)+240
  • Eritrea+291
  • Estonia(Eesti)+372
  • Ethiopia+251
  • Fiji+679
  • Finland+358
  • France+33
  • Gabon+241
  • Gambia+220
  • Georgia(საქართველო)+995
  • Germany+49
  • Ghana+233
  • Great Britain+44
  • Greece+30
  • Grenada+1 (473)
  • Guatemala+502
  • Guinea(Guinea Ecuatorial)+240
  • Guyana+592
  • Haiti+509
  • Honduras+504
  • Hong Kong(香港)+852
  • Hungary+36
  • Iceland+354
  • India(भारत)+91
  • Indonesia+62
  • Iran+98
  • Iraq(العراق))+964
  • Ireland+353
  • Israel(ישראל)+972
  • Italy(Italia)+39
  • Jamaica+1
  • Japan(日本)+81
  • Jordan+962
  • Kazakhstan+7
  • Kenya+254
  • Kiribati+686
  • Kuwait(الكويت)+965
  • Kyrgyzstan(Кыргызстан)+996
  • Laos(ລາວ)+856
  • Latvia(Latvija)+371
  • Lebanon(لبنان)+961
  • Lesotho+266
  • Liberia+231
  • Libya(ليبيا)+218
  • Liechtenstein+423
  • Lithuania(Lietuva)+370
  • Luxembourg+352
  • Madagascar(Madagasikara)+261
  • Malawi+256
  • Malaysia+60
  • Maldives+960
  • Mali+223
  • Malta+356
  • Marshall Islands+692
  • Mauritania(موريتانيا)+222
  • Mauritius(Moris)+230
  • Mexico(México)+52
  • Micronesia+691
  • Moldova(Republica Moldova)+373
  • Monaco+377
  • Mongolia(Монгол)+976
  • Montenegro(Crna Gora)+382
  • Morocco(المغرب)+212
  • Mozambique(Moçambique)+258
  • Myanmar(Burma)+95
  • Namibia(Namibië)+264
  • Nauru+674
  • Nepal(नेपाल)+977
  • Netherlands(Nederland)+31
  • New Zealand+64
  • Nicaragua+505
  • Niger(Nijar)+227
  • Nigeria+234
  • Niue+683
  • North Korea+850
  • North Macedonia+389
  • Norway(Norge)+47
  • Oman+968
  • Pakistan+92
  • Palau+680
  • Panama+507
  • Papua New Guinea+675
  • Paraguay+595
  • Peru(Perú)+51
  • Philippines+63
  • Poland(Polska)+48
  • Portugal+351
  • Qatar(قطر)+974
  • Romania(România)+40
  • Rwanda+250
  • Saint Kitts and Nevis+1 (869)
  • Saint Lucia+1 (758)
  • Saint Vincent and the Grenadines+1 (784)
  • Salvador+503
  • Samoa+685
  • San Marino+378
  • Sao Tome and Principe(São Tomé e Príncipe)+239
  • Saudi Arabia+966
  • Senegal(Sénégal)+221
  • Serbia(Србија)+381
  • Seychelles+248
  • Sierra Leone+232
  • Singapore+65
  • Slovakia(Slovensko)+421
  • Slovenia(Slovenija)+386
  • Solomon Islands+677
  • Somalia(Soomaaliya)+252
  • South Africa+27
  • South Sudan+211
  • Spain(España)+34
  • Sri Lanka(ශ්‍රී ලංකාව)+94
  • Sudan+211
  • Suriname+597
  • Sweden(Sverige)+46
  • Switzerland(Schweiz)+41
  • Syria+963
  • Tajikistan+992
  • Tanzania+255
  • Thailand(ไทย)+66
  • The Republic of Korea(대한민국)+82
  • Togo+228
  • Tonga+676
  • Trinidad and Tobago+1 (868)
  • Tunisia+216
  • Turkey(Türkiye)+90
  • Turkmenistan+993
  • Tuvalu+688
  • Uganda+256
  • Ukraine(Україна)+380
  • United Arab Emirates+971
  • Uruguay+598
  • USA+1
  • Uzbekistan(Oʻzbekiston)+998
  • Vanuatu+678
  • Vatican(Città del Vaticano)+39
  • Venezuela+58
  • Vietnam+84
  • Virgin Islands+1
  • Yemen(اليمن)+967
  • Zambia+260
  • Zimbabwe+263
This field is required
Your e-mail
Invalid e-mail entered
Registration completed successfully!
An error occurred. Please inform the administrator
You have sent many applications. try later
Your name and surname
This field is required
My city
This field is required
Your e-mail
Invalid e-mail entered
Message
This field is required
Pre-entry
Registration completed successfully!
An error occurred. Please inform the administrator
You have sent many applications. try later
Your name and surname
This field is required
Child's name
This field is required
My city
This field is required
Your phone
This field is required
Your e-mail
Invalid e-mail entered
Start month
October 2026
November 2026
December 2026
Request a call
Thank you, the administrator will contact you as soon as possible.
Something went wrong, try to send the request later.
You have sent many applications. try later
Your name and surname
This field is required
Your phone
+1
This field is required
Something went wrong, try to send the request later.
You have sent many applications. try later
Your name and surname
This field is required
Your phone
This field is required
Order certificate
Thank you, the administrator will contact you as soon as possible.
Something went wrong, try to send the request later.
You have sent many applications. try later
Your name and surname
This field is required
My city
This field is required
Your phone
This field is required
Your e-mail
Invalid e-mail entered
Pay for the classes
Thank you!
Registration form is submitted, manager will contact you shortly!
An error occurred. Please inform the administrator
You have sent many applications. try later
Name and surname of the child
This field is required
Your e-mail
Invalid e-mail entered
The amount of payment
Please type an integer number
Give feedback
Thank you for your feedback.
Something went wrong, try to send the request later.
You have sent many applications. try later
Your name and surname
This field is required
Your photo
Your e-mail
Invalid e-mail entered
Rate us
Review
This field is required
Registration completed successfully!
Close
For registration and with any questions, please contact us by phone +46 76-584 77 40 or email [email protected]
Close
Close
Выберите языкChoose a languageТілді таңдаңызВиберіть мовуSélectionnez la langueSprache wählen
Choose a language
RU
EN
KZ
UA
FR
DE
OK
Preview