We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,868 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Simple dictionary use

4
By Georgi Christov on Nov 22nd, 2009 5:40 am

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 :)

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 :)

Paul Thompson
Veteran Poster
1,119 posts since May 2008
Reputation Points: 264
Solved Threads: 183
Skill Endorsements: 1

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!

vegaseat
DaniWeb's Hypocrite
Moderator
6,475 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,611
Skill Endorsements: 36

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

masterofpuppets
Posting Whiz in Training
272 posts since Jul 2009
Reputation Points: 20
Solved Threads: 74
Skill Endorsements: 0

oh wait is there a way to actually change this?

masterofpuppets
Posting Whiz in Training
272 posts since Jul 2009
Reputation Points: 20
Solved Threads: 74
Skill Endorsements: 0

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

tags as I believe someone else suggested

leegeorg07
Posting Pro in Training
428 posts since Jul 2008
Reputation Points: 35
Solved Threads: 33
Skill Endorsements: 0

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...

masterofpuppets
Posting Whiz in Training
272 posts since Jul 2009
Reputation Points: 20
Solved Threads: 74
Skill Endorsements: 0

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
DaniWeb's Hypocrite
Moderator
6,475 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,611
Skill Endorsements: 36

@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!

vegaseat
DaniWeb's Hypocrite
Moderator
6,475 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,611
Skill Endorsements: 36

@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 {}:

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) ]

Thanks! I updated your original tutorial with this version!
vegaseat

masterofpuppets
Posting Whiz in Training
272 posts since Jul 2009
Reputation Points: 20
Solved Threads: 74
Skill Endorsements: 0

hope this looks better :)

masterofpuppets
Posting Whiz in Training
272 posts since Jul 2009
Reputation Points: 20
Solved Threads: 74
Skill Endorsements: 0

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

masterofpuppets
Posting Whiz in Training
272 posts since Jul 2009
Reputation Points: 20
Solved Threads: 74
Skill Endorsements: 0
bugatti veyron
Newbie Poster
1 post since Feb 2010
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

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

kitjo
Light Poster
42 posts since Aug 2009
Reputation Points: 7
Solved Threads: 0
Skill Endorsements: 0

Merci :)

Boubakr
Newbie Poster
16 posts since Jan 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.1203 seconds using 2.83MB