Simple dictionary use

Updated masterofpuppets 5 Tallied Votes 998 Views Share

Here's a simple tutorial on dictionaries in Python:

Dictionaries:

Dictionaries are similar to other compound types except that they can use any immutable type as an index. One way to
create a dictionary is to start with the empty dictionary and add items. The empty dictionary is denoted {}:

end2sp = {}
end2sp[ "one" ] = "uno"
end2sp[ "two" ] = "dos"

We can print the current value of the dictionary in the usual way:

print eng2sp 
# -->  { "one":"uno", "two":"dos" }

The elements of a dictionary appear in a coma-separated list. Each entry contains an index and a value separated by
colon. The indices are called keys, so the elements are called key-value pairs.
Another way to create a dictionary is to provide a list of key-value pairs using the same syntax as the previous output.

eng2sp = { "one":"uno", "two":"dos", "three":"tres" }
print eng2sp  
# -->  { "one":"uno", "three":"tres", "two":"dos" }

Note: the key-value pairs are not in order but the elements in a dictionary are never indexed with integers so there
is no reason to worry about that. Instead we look up the key:

print eng2sp[ "two" ]  
# -->  "dos"

Dictionary operations:

The 'del' statement removes key-value pair from a dictionary.

inventory = { "apples":430, "bananas":312, "oranges":525 }
del inventory[ "oranges" ]
print inventory  
# -->  { "apples":430, "bananas":312 }

The 'len' function also works on dictionaries; it returns the number of key-value pairs.

len( invenroty ) returns 2


Dictionary methods:

A method is similar to a function - it takes and returns a value - but the syntax is different. For example, the keys
method takes a dictionary and returns a list of the keys that appear, but instead of the function syntax keys( eng2sp )
we use the method syntax eng2sp.keys()

print eng2sp.keys()  
# -->  [ "one", "three", "two" ]

The values method is similar; it returns a list of values in the dictionary:

print eng2sp.values() 
# -->  [ "uno", "tres", "dos" ]

The items method returns both, in the form of a list of tuples - one for each key-value pair

print eng2sp.items()  
# -->  [ ("one", "uno"), ("two", "dos"), ("three", "tres") ]

If a method takes an argument, it uses the same syntax as a function call. For example, the method has_key takes a key
and returns True if the key appears in the dictionary:

eng2sp.has_key( "one" )  
# -->  True  ( using the previous example dictionary )
eng2sp.has_key( "four" )
# -->  False  ( using the previous example dictionary )

Note: if you try to invoke a method without specifying an object, you get an error.


Aliasing and copying:

Because dictionaries are mutable, you need to be aware of aliasing. Whenever two variables refer to the same object,
changes to one affect the other. If you want to modify a dictionary and keep a copy of the original, use the copy method.

opposites = { "up":"down", "right":"left", "wrong":"true" }
alias = opposites
copy = opposites.copy()

alias[ "right" ] = "left"
print opposites[ "right" ]  
# -->  "left"

copy[ "right" ] = "privilege"
print opposites[ "right" ]  
# --> "left" again because we made a deep copy of the dictionary

e.g. Write a function that returns the number of letters in a string.
solution:

def letterCount( string ):
    letters = {}
    for l in string:
        letters[ l ] = letters.get( letter, 0 ) + 1
    return letters

How's it work:
The 'get' method takes two parameters - the first one is the key to be found in the dictionary and the second
parameter is the value to be returned if the key is not found. If the key is in the dictionary, its value is
corresponding value is returned.
So if 'l' is not in the dictionary letters[ l ] = 0 + 1, i.e. 'l' is a new letter in the dictionary.

Output:

letterItems = letterCount( "Mississippi" )
print letterItems  
# -->  { "M":1, "s":4, "p":2, "i":4 }

You can also display the results in alphabetical order by sorting the keys:

tmp = letterItems.items()
tmp.sort()
   
print tmp 
# -->  [ ("M", 1), ("i", 4), ("p", 2), ("s", 4) ]

Resource: How To Think Like A Computer Scientist and some of my own stuff :)

Hope it is helpful :)

lllllIllIlllI 178 Veteran Poster

You really need to use [code]

[/code] tags otherwise it looks messy.

Also, provide a link to where you referenced things from, when referencing directly it is also a good idea to surround the text in quotation marks to indicate this is directly from a reference.

Otherwise its good :)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I truly frown on folks using Python Shell code for tutorials, it looks ugly, messy, confusing to beginners, and not Pythonic at all! Python prides itself on readable syntax.

Thanks for the update and correction!

Member Avatar for masterofpuppets
masterofpuppets

thanks the comment I'll try to modify it..... and of course avoid this next time :)

Member Avatar for masterofpuppets
masterofpuppets

oh wait is there a way to actually change this?

Member Avatar for leegeorg07
leegeorg07

yeah, you simply need to click edit and change it there, also could you put in some

tags as I believe someone else suggested

Member Avatar for masterofpuppets
masterofpuppets

yeah, you simply need to click edit and change it there, also could you put in some tags as I believe someone else suggested

I don't see the edit anymore it was there yesterday I think, so I cannot edit it :( all I see is quick reply...

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Also note ...

eng2sp = { "one":"uno", "two":"dos", "three":"tres" }

# works in Python2, but not Python3
# Python3 gives error ...
# AttributeError: 'dict' object has no attribute 'has_key'
#print( eng2sp.has_key( "one" ) )  # True

# works with Python2 and Python3
print( "one" in eng2sp )  # True
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

@masterofpuppets:

I like the overall tutorial, so simply make your corrections and post it here. Mark it clearly as (first line):
CORRECTED TUTORIAL
I will replace the first version for you.
Thanks for the effort!

Member Avatar for masterofpuppets
masterofpuppets

@vegaseat

ok here goes :)

Well as you mentioned this works for Python2 though. I'll post the whole thing again but with the corrections included:

Dictionaries:

Dictionaries are similar to other compound types except that they can use any immutable type as an index. One way to
create a dictionary is to start with the empty dictionary and add items. The empty dictionary is denoted {}:

eng2sp = {}
eng2sp[ "one" ] = "uno"
eng2sp[ "two" ] = "dos"

We can print the current value of the dictionary in the usual way:

print eng2sp 
# -->  { "one":"uno", "two":"dos" }

The elements of a dictionary appear in a coma-separated list. Each entry contains an index and a value separated by
colon. The indices are called keys, so the elements are called key-value pairs.
Another way to create a dictionary is to provide a list of key-value pairs using the same syntax as the previous output.

eng2sp = { "one":"uno", "two":"dos", "three":"tres" }
print eng2sp  
# -->  { "one":"uno", "three":"tres", "two":"dos" }

Note: the key-value pairs are not in order but the elements in a dictionary are never indexed with integers so there
is no reason to worry about that. Instead we look up the key:

print eng2sp[ "two" ]  
# -->  "dos"

Dictionary operations:

The 'del' statement removes key-value pair from a dictionary.

inventory = { "apples":430, "bananas":312, "oranges":525 }
del inventory[ "oranges" ]
print inventory  
# -->  { "apples":430, "bananas":312 }

The 'len' function also works on dictionaries; it returns the number of key-value pairs.

len( inventory )  returns 2

Dictionary methods:

A method is similar to a function - it takes and returns a value - but the syntax is different. For example, the keys
method takes a dictionary and returns a list of the keys that appear, but instead of the function syntax keys( eng2sp )
we use the method syntax eng2sp.keys()

print eng2sp.keys()  
# -->  [ "one", "three", "two" ]

The values method is similar; it returns a list of values in the dictionary:

print eng2sp.values() 
# -->  [ "uno", "tres", "dos" ]

The items method returns both, in the form of a list of tuples - one for each key-value pair

print eng2sp.items()  
# -->  [ ("one", "uno"), ("two", "dos"), ("three", "tres") ]

If a method takes an argument, it uses the same syntax as a function call. For example, the method has_key takes a key
and returns True if the key appears in the dictionary:

eng2sp.has_key( "one" )  
# -->  True  ( using the previous example dictionary )
eng2sp.has_key( "four" )
# -->  False  ( using the previous example dictionary )

Note: if you try to invoke a method without specifying an object, you get an error.

Aliasing and copying:

Because dictionaries are mutable, you need to be aware of aliasing. Whenever two variables refer to the same object,
changes to one affect the other. If you want to modify a dictionary and keep a copy of the original, use the copy method.

opposites = { "up":"down", "right":"left", "wrong":"true" }
alias = opposites
copy = opposites.copy()

alias[ "right" ] = "left"
print opposites[ "right" ]  
# -->  "left"

copy[ "right" ] = "privilege"
print opposites[ "right" ]  
# --> "left" again because we made a deep copy of the dictionary

e.g. Write a function that returns the number of letters in a string.
solution:

def letterCount( string ):
    letters = {}
    for l in string:
        letters[ l ] = letters.get( letter, 0 ) + 1
    return letters

How's it work:
The 'get' method takes two parameters - the first one is the key to be found in the dictionary and the second
parameter is the value to be returned if the key is not found. If the key is in the dictionary, its value is
corresponding value is returned.
So if 'l' is not in the dictionary letters[ l ] = 0 + 1, i.e. 'l' is a new letter in the dictionary.

Output:

letterItems = letterCount( "Mississippi" )
print letterItems  
# -->  { "M":1, "s":4, "p":2, "i":4 }

You can also display the results in alphabetical order by sorting the keys:

tmp = letterItems.items()
tmp.sort()

print tmp 
# -->  [ ("M", 1), ("i", 4), ("p", 2), ("s", 4) ]

Thanks! I updated your original tutorial with this version!
There are some changes with Python3. vegaseat

Member Avatar for masterofpuppets
masterofpuppets

hope this looks better :)

Member Avatar for masterofpuppets
masterofpuppets

thanks a lot :) sry for the previous one - I'm still learning :) this one really is more readable..

bugatti veyron 0 Newbie Poster

{}

kitjo -3 Light Poster

can i do it from the database not from the codes? Example SQL

Nick Evan commented: Are you serious? -3
Boubakr 0 Newbie Poster

Merci :)

Alf1# 0 Newbie Poster

Hi Georgi (MasterOfPuppets),
Thanks for this tutorial.
I'm new to Python and am teaching myself so forgive me if what I ask next is stupid. You start off your first 3 lines of code with end2sp but then the code changes to eng2sp: is that just a typo, i.e. should all the code read end2sp?

Alf1# 0 Newbie Poster

Hi Georgi,
I've spotted another typo in the area relating to the len function: you've typed: len( invenroty ) returns 2 instead of inventory.
Can I suggest you actually change this to: print(len(inventory))?
I'm enjoying your tutorial.
Regards, Alfred

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.