Skip to main content

What It's Dictionary In Python Programming

Know What It's Dictionary In Python Programming

At the material then, we've studied the list data structure in python program that is capable of storing a wide range of values ​​that has a variety of data types. List is usually used to store a variety of data collection.

But it turns out, the list has its drawbacks.

Lack of List: the list can not use keywords to access an item or the value. Can only be used by calling the index number only.

But do not worry ya ...

Weakness on the list now can be completed by the Dictionary.

On this matter, we will learn the basic things that should be known about Dictionary in python program.

The following important things:

What is a Dictionary in Python Programming?

Dictionary is a data structure that looks like a dictionary. There is a key word then there the value well. Keyword must be unique (not the same as the others), while the value may be filled with just about anything.

Example Code:
me {
    "name": "FajarYusuf",
    "url": "https://www.fajaryusuf.com"
}


In the example above we are coding to create a Dictionary called me and filled in the name and URL. name and url is the key word (key) that we will use to access the value in it.

This is the difference Dictionary compared with lists and tuples . Dictionary have keywords that can be text, and could also figure, while for lists and tuples only use an index is either a number in order to access its value.

In other programming languages (eg PHP), the Dictionary also known as associative arrays .

make Dictionary

Things that must exist in the manufacture Dictionary is:

  • name Dictionary,
  • Keywords,
  • Value,
  • Open the lid and Dictionary should use curly braces.
Among the key and value must be separated with a colon (:) and when there is more than one item or value, then separated by a comma (,).

Examples of coding an item:
name_dict = {
    "key": "value"
}
Examples of coding of three items:
name_dict = {
    "key1": "value",
    "key2": "value",
    "key3": "value"
}
The contents of the Dictionary can be the following data types:

  • String
  • Integer
  • objects
  • List
  • Tuple
  • Dictionary
  • etc.
Example Code:
FajarYusuf= {
    "name": "FajarYusuf",
    "age": 25,
    "hobby": ["coding", "nggame", "ngband"],
    "get married": True,
    "sosmed": {
        "facebook": "FajarYusuf",
        "twitter": "@cibinongcreative"
    }
}
Here are the contents of the Dictionary above:
  • name contains the string value "FajarYusuf"
  • age contains an integer with a value 25
  • hobby contains a list of strings
  • get married is boolean True
  • and sosmed contains Dictionary 

using Constructors

In addition to using the above, we also can make the Dictionary of constructor dict () with the parameter keys and values.

Example Code :
color_fruit = dict (orange = "orange", apple = "red", banana = "yellow")
It will generate the dictionary as follows:
{ 'Orange': 'orange', 'apple', 'red', 'banana', 'yellow'}

Accessing Item Values ​​of Dictionary

We already know how to create the Dictionary, now let us learn how to access them.

How to access the same as accessing the list. But the key words used are not numbers, but the keywords we have set in the Dictionary.

Example Code :
#CreateDictionary
fajaryusuf = {
    "name": "Fajar Yusuf",
    "age": 25,
    "hobby": ["coding", "nggame", "ngband"],
    "get married": True,
    "sosmed": {
    "Facebook": "Fajar Yusuf",
        "twitter": "@cibinongcreative"
    }
}
# Access the contents of the dictionary
print ("My name is %s"% fajaryusuf ["name"])
print ("Twitter: %s"% fajaryusuf ["sosmed"] ["twitter"])


Results output:

What It's Dictionary In Python Programming

In addition to the above manner, we can also access the value Dictionary with method get ().

Example Code:

#CreateDictionary
fajaryusuf= {
    "name": "FajarYusuf",
    "age": 25,
    "hobby": ["coding", "nggame", "ngband"],
    "get married": True,
    "sosmed": {
        "facebook": "FajarYusuf",
        "twitter": "@cibinongcreative"
    } 
}
# Access the contents of the dictionary
print(fajaryusuf.get("name"))
print(fajaryusuf.get("age"))

The result:

Know What It's Dictionary In Python Programming

using Recurrence

To display the output of all the contents of the Dictionary, we can use the loop like this:
# CreateDictionary
web = {
    "name": "FajarYusuf.Com",
    "url": "https://www.fajaryusuf.com",
    "rank": "5"
}
# Print the contents of the dictionary with repetition
for key in web:
    print(web[key])
The result:
Know What It's Dictionary In Python Programming

We can also do it like the following code:
web = {
    "name": "FajarYusuf.Com",https://www.fajaryusuf.com",
    "url": "
    "rank": "1"
}
for key, val in web.items():
    print("%s : %s" % (key, val))
The result:

Know What It's Dictionary In Python Programming

Changing Item Values ​​Dictionary

Dictionary is mutable, which means that its value can be changes as needed. To change the value of the Dictionary, we can do like this coding:

name_dic [ "key"] = "New Value"
Example:

# Making Online Dictionary 
skill = { 
    "key": "Python", 
    "other": [ "CSS", "JAVASCRIPT", "HTML"] 

# Print cartridge skill main 
print (skill [ "key"]) 
# edit any skill The main 
skill [ "key"] = "Ruby" 
# Print the contents of the main skill 
print (skill [ "key"])
The value of key 'key' will be changed from Python to Ruby, he will produce:
Python
Ruby


Removing items from the Dictionary

To remove the value of the Dictionary, we can use the command del and method pop ().

Method pop () is a method that serves to remove items from the dictionary while del function is a function to remove a variable from memory.

Coding example to remove it using del:
>>> del skill["main"]
>>> skill
{'other': ['PHP', 'Java', 'HTML']}

Sample Coding remove by using the method pop ():
>>> skill.pop("main")
'Rust'
>>> skill
{'other': ['PHP', 'Java', 'HTML']}

And if we want to remove all the dictionary at once, we can use the method clear ().

Example Code:
skill.clear()


Adding items to Dictionary

We can use the method update () to add content to Dictionary. Parameters such as Dictionary.

Also serves to add, this method also serves to change the dictionary when the key is inserted are built.

Example Code:
# Create dictionary user
user = {
    "name": "FajarYusuf"
}
# add password
user.update({"password": "P@ssw0rd"})
print(user)
# update name
user.update({"name": "CodingMania"})
print(user)
The result:

{'name': 'FajarYusuf', 'password': 'P@ssw0rd'}
{'name': 'CodingMania', 'password': 'P@ssw0rd'}

Taking the Long Dictionary

To retrieve the amount of data (count) or long-Dictionary, we can use the function len ().

Example Code:
# Make Dictonary 
books = { 
    "python": "Mastering Python within 24 hours", 
    "java": "Tutorial Learning Python for Beginners", 
    "php": "Creating a web application with a CSS" 

# print the amount of data that is in dictionary 
print ( "total book:% d"% len (books))
The result:
total book: 3

Comments

Popular posts from this blog

Contoh Program C++ : Konversi Bilangan Hexadesimal, Oktal , Biner.

Hai Pembaca FajarYusuf.Com yang pintar dan berwawasan tinggi, kali ini FajarYusuf.Com akan post Contoh Program C++ : Konversi Bilangan Hexadesimal, Oktal , Biner . Mari kita membuat program konversi bilangan yang sangat mudah di buat dengan menggunakan bahasa pemrograman C++. Yaitu dengan menggunakan type data long, untuk Hexadesimal dengan rumus : <<hex<<desimal (merubah dari bilangan Desimal ke Hexadesimal) , untuk Oktal dengan rumus : <<oct<<desimal (merubah dari bilangan Desimal ke Oktal). Dan untuk biner dilakukan pembagian 2. Contoh Coding Program C++ Konversi Bilangan: #include<iostream> using namespace std; int main() { long desimal, pembagi=1073741824, bit; cout<<"Nilai Desimal : "; cin>>desimal; cout<<"Hexadesimal = "<<hex<<desimal<<endl; cout<<"Oktal = "<<oct<<desimal<<endl;
Les rumeurs sur les rencontres avec RM ont d’abord été propagées par un YouTuber, qui a déclaré que RM sortait avec une femme du cercle non-célébrité, mais qu’elle était riche.  La rumeur est née à cause d’une photo de RM avec un caniche, qui aurait appartenu à la femme. Les rumeurs se sont rapidement propagées sur internet et ont fait se demander nombre de fans: est-il vrai que le leader du groupe BTS a un amant? RM a ensuite répondu aux rumeurs via Weteverse jeudi 30/12/201. “Je ne connais pas du tout cette personne. Le caniche est le caniche de mon ami,” a déclaré RM, cité à partir d’un t weet  appartenant à @btsinthemoment. namjoon weverse moment 🐨 i dont know the person at all and the poodle is my friends poodle ^^; pic.twitter.com/okz0AIpVnc — 윤서⁷ (@btsinthemoment) December 31, 2021 Big Hit a également nié les allégations dans une déclaration publiée par  AllKPop .  “Les rumeurs de rencontres sur RM ne sont pas vraies,” a déclaré Big Hit, vendredi (31/12). Et apparemment, dans

Opisyal na Inilabas ni Adele ang Bagong Album na "30"

Opisyal na inilabas ni Adele ang kanyang pinakabagong album na pinamagatang “30” noong Biyernes (11/19/2021).  Nakatanggap ang bagong album ng mgapositibong pagsusuri mula sa mga kritiko ng musika. Ayon sa Rolling Stone , ang “30” ay ang pinakamahusay na album ni Adele. Mayroong 12 kanta sa “30” album na ito, isa na rito ang hit single na pinamagatang  Easy On Me .  Sa simula ng album, maririnig mo ang  Strangers By Nature— isang kantang puno ng patula na liriko. At sa dulo ay ang kantang  Love Is A Game , na nagsasalaysay ng karanasan ni Adele sa sakit na dulot ng pag-ibig. Sa  Metacritic  , nakatanggap ang bagong album ni Adele ng  metascore  na 89% mula sa 12  review  at nasa numero 8 sa listahan ng  Best Albums ng 2021 .  Habang nasa Apple Music Indonesia, ang LP “30” ay unang niraranggo sa Mga   Nangungunang Album. Adele sa British Vogue magazine (instagram.com/britishvogue). Ang album na ito ay inspirasyon ng diborsiyo ni Adele kay Simon Konecki. Sa isang pakikipanayam sa