1,105,447 Community Members

Simple dictionary use

Member Avatar
(masterofpuppets)
Reputation Points: 5 [?]
Q&As Helped to Solve: 74 [?]
Skill Endorsements: 0 [?]
 
4
 

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

Member Avatar
Paul Thompson
Veteran Poster
1,095 posts since May 2008
Reputation Points: 178 [?]
Q&As Helped to Solve: 189 [?]
Skill Endorsements: 3 [?]
 
0
 

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

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
0
 

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
masterofpuppets
Posting Whiz in Training
272 posts since Jul 2009
Reputation Points: 5 [?]
Q&As Helped to Solve: 74 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
masterofpuppets
Posting Whiz in Training
272 posts since Jul 2009
Reputation Points: 5 [?]
Q&As Helped to Solve: 74 [?]
Skill Endorsements: 0 [?]
 
0
 

oh wait is there a way to actually change this?

Member Avatar
leegeorg07
Posting Pro in Training
428 posts since Jul 2008
Reputation Points: 23 [?]
Q&As Helped to Solve: 33 [?]
Skill Endorsements: 0 [?]
 
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

Member Avatar
masterofpuppets
Posting Whiz in Training
272 posts since Jul 2009
Reputation Points: 5 [?]
Q&As Helped to Solve: 74 [?]
Skill Endorsements: 0 [?]
 
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...

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
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
Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
0
 

@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
masterofpuppets
Posting Whiz in Training
272 posts since Jul 2009
Reputation Points: 5 [?]
Q&As Helped to Solve: 74 [?]
Skill Endorsements: 0 [?]
 
0
 

@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

Member Avatar
masterofpuppets
Posting Whiz in Training
272 posts since Jul 2009
Reputation Points: 5 [?]
Q&As Helped to Solve: 74 [?]
Skill Endorsements: 0 [?]
 
0
 

hope this looks better :)

Member Avatar
masterofpuppets
Posting Whiz in Training
272 posts since Jul 2009
Reputation Points: 5 [?]
Q&As Helped to Solve: 74 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
bugatti veyron
Newbie Poster
1 post since Feb 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

{}

Member Avatar
kitjo
Light Poster
42 posts since Aug 2009
Reputation Points: -3 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
-2
 

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

Member Avatar
Boubakr
Newbie Poster
16 posts since Jan 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Merci :)

You
Post:
Start New Discussion
View similar articles that have also been tagged: