1.11M Members

Simple dictionary use

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

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

 
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!

 
0
 

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

 
0
 

oh wait is there a way to actually change this?

 
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

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

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

 
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

 
0
 

hope this looks better :)

 
0
 

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

 
0
 

{}

 
-2
 

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

 
0
 

Merci :)

Isn't it about time forums rewarded their contributors?

Earn rewards points for helping others. Gain kudos. Cash out. Get better answers yourself.

It's as simple as contributing editorial or replying to discussions labeled or OP Kudos

You
This is an OP Kudos discussion and contributors may be rewarded
Post:
Start New Discussion
View similar articles that have also been tagged: