Python Dictionary(Dict): Update, Cmp, Len, Sort, Copy, Items, str Example

Dictionaries are another example of a data structure. A dictionary is used to map or associate things you want to store the keys you need to get them. A dictionary in Python is just like a dictionary in the real world. Python Dictionary are defined into two elements Keys and Values.

  • Keys will be a single element
  • Values can be a list or list within a list, numbers, etc.

In this tutorial, we are going to learn,

  • We have the original dictionary (Dict) with the name and age of the boys and girls together
  • But we want boys list separate from girls list, so we defined the element of boys and girls in a separate dictionary name “Boys” and “Girls.”
  • Now again we have created new dictionary name “studentX” and “studentY”, where all the keys and values of boy dictionary are copied into studentX, and the girls will be copied in studentY
  • So now you don’t have to look into the whole list in main dictionary( Dict) to check who is boy and who is girl, you just have to print studentX if you want boys list and StudentY if you want girls list
  • So, when you run the studentX and studentY dictionary, it will give all the element present in the dictionary of “boys” and “girls” separately

Updating Dictionary

You can also update a dictionary by adding a new entry or a key-value pair to an existing entry or by deleting an existing entry. Here in the example we will add another name “Sarah” to our existing dictionary.

Python 2 Example

 

Summary:

Dictionaries in a programming language is a type of data-structure used to store information connected in someway. Python Dictionary are defined into two elements Keys and Values. Dictionaries do not store their information in any particular order, so you may not get your information back in the same order you entered it.

  • Keys will be a single element
  • Values can be a list or list within a list, numbers, etc.
  • More than one entry per key is not allowed ( no duplicate key is allowed)
  • The values in the dictionary can be of any type while the keys must be immutable like numbers, tuples or strings.
  • Dictionary keys are case sensitive- Same key name but with the different case are treated as different keys in Python dictionaries.
top
X
Welcome to Our Website
Welcome to WPBot
wpChatIcon