banner



How To Create A Python Dictionary

You are here: Home / Dictionary / Python Dictionary – How To Create Dictionaries In Python

Dictionaries in Python are a list of items that are unordered and can be changed by use of built in methods. Dictionaries are used to create a map of unique keys to values.

About Dictionaries in Python

To create a Dictionary, use {} curly brackets to construct the dictionary and [] square brackets to index it.

Separate the key and value with colons : and with commas , between each pair.

Keys must be quoted, for instance: "title" : "How to use Dictionaries in Python"

As with lists we can print out the dictionary by printing the reference to it.

A dictionary maps a set of objects (keys) to another set of objects (values) so you can create an unordered list of objects.

Dictionaries are mutable, which means they can be changed.

The values that the keys point to can be any Python value.

Dictionaries are unordered, so the order that the keys are added doesn't necessarily reflect what order they may be reported back. Because of this, you can refer to a value by its key name.

Create a new dictionary

# In order to construct a dictionary you can start with an empty one.

            >>> mydict={}          

# This will create a dictionary, which has an initially six key-value pairs, where iphone* is the key and years the values

            released = { 		"iphone" : 2007, 		"iphone 3G" : 2008, 		"iphone 3GS" : 2009, 		"iphone 4" : 2010, 		"iphone 4S" : 2011, 		"iphone 5" : 2012 	} print released                      
                          >>Output {'iphone 3G': 2008, 'iphone 4S': 2011, 'iphone 3GS': 2009, ' 	iphone': 2007, 'iphone 5': 2012, 'iphone 4': 2010}                      

Add a value to the dictionary

You can add a value to the dictionary in the example below. In addition, we'll go ahead and change the value to show how dictionaries differ from a Python Set.

            #the syntax is: mydict[key] = "value" released["iphone 5S"] = 2013 print released >>Output {'iphone 5S': 2013, 'iphone 3G': 2008, 'iphone 4S': 2011, 'iphone 3GS': 2009, 'iphone': 2007, 'iphone 5': 2012, 'iphone 4': 2010}                      

Remove a key and it's value

You can remove an element with the del operator

            del released["iphone"] print released >>output {'iphone 3G': 2008, 'iphone 4S': 2011, 'iphone 3GS': 2009, 'iphone 5': 2012, 'iphone 4': 2010}                      

Check the length

The len() function gives the number of pairs in the dictionary. In other words, how many items are in the dictionary.

            print len(released)                      

Test the dictionary

Check if a key exists in a given dictionary by using the in operator like this:

            >>> my_dict = {'a' : 'one', 'b' : 'two'} >>> 'a' in my_dict True >>> 'b' in my_dict True >>> 'c' in my_dict False                      

or like this in a for loop

            for item in released:     if "iphone 5" in released:         print "Key found"         break     else:         print "No keys found" >>output Key found                      

Get a value of a specified key

            print released.get("iphone 3G", "none")                      

Print all keys with a for loop

            print "-" * 10 print "iphone releases so far: " print "-" * 10 for release in released:     print release  >>output ---------- iphone releases so far:  ---------- iphone 3G iphone 4S iphone 3GS iphone iphone 5 iphone 4                      

Print all key and values

            for key,val in released.items():     print key, "=>", val  >>output iphone 3G => 2008 iphone 4S => 2011 iphone 3GS => 2009 iphone => 2007 iphone 5 => 2012 iphone 4 => 2010                      

Get only the keys from the dictionary

            phones = released.keys() print phones                      

# or print them out like this:

            print "This dictionary contains these keys: ", " ".join(released) >>iphone 3G iphone 4S iphone 3GS iphone iphone 5 iphone 4                      

# or like this:

            print "This dictionary contains these keys: ", " ", released.keys() >>['iphone 3G', 'iphone 4S', 'iphone 3GS', 'iphone', 'iphone 5', 'iphone 4']                      

Printing the values

Elements may be referenced via square brackets, for example:
print released["iphone"]

            print "Values: ", for year in released:     releases= released[year]     print releases  >>output: Values: 2008 2011 2009 2007 2012 2010                      

Printing with pprint

            pprint.pprint(released)                      

Sorting the dictionary

In addition to printing, let's sort the data so we have an expected output.

            for key, value in sorted(released.items()):     print key, value >>output: ('iphone', 2007) ('iphone 3G', 2008) ('iphone 3GS', 2009) ('iphone 4', 2010) ('iphone 4S', 2011) ('iphone 5', 2012) """                      
            for phones in sorted(released, key=len):     print phones, released[phones]  >>output: iphone 2007 iphone 5 2012 iphone 4 2010 iphone 3G 2008 iphone 4S 2011 iphone 3GS 2009                      

Counting

Finally, let's show the value of using a counter in the dictionary to display the number of items.

            count = {} for element in released:     count[element] = count.get(element, 0) + 1 print count  >>output: {'iphone 3G': 1, 'iphone 4S': 1, 'iphone 3GS': 1, 'iphone': 1,  'iphone 5': 1, 'iphone 4': 1}                      

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

How To Create A Python Dictionary

Source: https://www.pythonforbeginners.com/dictionary/how-to-use-dictionaries-in-python

Posted by: khangwartan.blogspot.com

0 Response to "How To Create A Python Dictionary"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel