Experimenting with Dictionaries (Python)

vegaseat 3 Tallied Votes 969 Views Share

A dictionary in Python is an unordered set of key:value pairs. I show you how to initialize, create, load, display, search, copy and otherwise manipulate this interesting container. Like the name says, it is the closest thing to a dictionary.

Tcll commented: very nice, mentions everything I've played with. =D +4
# experimenting with the Python dictionary
# a seemingly unordered set of key:value pairs, types can be mixed
# Python23 tested     vegaseat     13feb2005

# initialize a dictionary, here a dictionary of roman numerals
romanD = {'I':1,'II':2,'III':3,'IV':4,'V':5,'VI':6,'VII':7,'VIII':8,'IX':9}
print "A dictionary is an unordered set of key:value pairs:"
print romanD

# create an empty dictionary
D1 = {}

# show empty dictionary contents and length (number of item/pairs)
print "Empty Dictionary contains:"
# shows  {}
print D1
# shows Length = 0
print "Length = ", len(D1)

# add/load new key:value pairs by using indexing and assignment
# here 'eins' is the key, 'one' is the key value
# the start of a german to english dictionary
D1['null'] = 'zero'
D1['eins'] = 'one'
D1['zwei'] = 'two'
D1['drei'] = 'three'
D1['vier'] = 'four'

# print loaded dictionary and length
# the dictionary key order allows for most efficient searching
print "Dictionary now contains (notice the seemingly random order of pairs):"
print D1
print "Length = ",len(D1)

# find the value by key (does not change dictionary)
print "The english word for drei is ", D1['drei']
# better
if 'drei' in D1:
    print "The english word for drei is ", D1['drei']

# create a list of the values in the dictionary
L1 = D1.values()
# the list can be sorted, the dictionary itself cannot
L1.sort()
print "A list of values in the dictionary (sorted):"
print L1

# create a list of dictionary keys
L2 = D1.keys()
L2.sort()
print "A list of the dictionary keys (sorted):"
print L2

# does the dictionary contain a certain key?
if D1.has_key('null'):
    print "Key 'null' found!"
else:
    print "Key 'null' not found!"

# copy dictionary D1 to D2 (the order may not be the same)
D2 = D1.copy()
print "Dictionary D1 has been copied to D2:"
print D2

# delete an entry
del D2['zwei']
print "Dictionary D2 after 'zwei' has been deleted:"
print D2

# extract the value and remove the entry
# pop() changes the dictionary, use e3 = D2['drei'] for no change
e3 = D2.pop('drei')
print "Extract value for key = 'drei' and delete item from dictionary:"
print e3
print "Dictionary D2 after 'drei' has been popped:"
print D2

print

str1 = "I still miss you baby, but my aim's gettin' better!"
print str1
print "Count the characters in the above string:"
# create an empty dictionary
charCount = {}
for char in str1:
    charCount[char] = charCount.get(char, 0) + 1
print charCount
print
if 't' in charCount:
    print "There are %d 't' in the string" % charCount['t']

print

str2 = "It has been a rough day. I got up this morning put on a shirt and a"
str2 = str2 + " button fell off. I picked up my briefcase and the handle came off."
str2 = str2 + " Now I am afraid to go to the bathroom."
print str2
print "Count the words in the above string, all words lower case:"
# create a list of the words
wordList = str2.split(None)
# create an empty dictionary
wordCount = {}
for word in wordList:
    # convert to all lower case
    word = word.lower()
    # strip off any trailing period, if needed do other punctuations
    if '.' in word:
        word = word.rstrip('.')
    # load key:value pairs by using indexing and assignment
    wordCount[word] = wordCount.get(word, 0) + 1
print wordCount
print
# put keys into list and sort
keyList = wordCount.keys()
keyList.sort()
# display words and associated count in alphabetical order
for keyword in keyList:
    print keyword, "=", wordCount[keyword]

# put the dictionary pairs into a list, use the romanD dictionary
romanList = []
for key, value in romanD.items():
    # put value first for a meaningful sort
    romanList.append((value, key))
romanList.sort()
print "\nThe roman numeral dictionary put into a (value,pair) list then sorted:"
print romanList
print "\nList them as pairs on a line:"
for i in xrange(len(romanList)):
    print romanList[i][0],'=', romanList[i][1]

print

# split the romanD dictionary into two lists
print "Splitting the romanD dictionary into two lists:"
romankeyList = []
romanvalueList = []
for key, value in romanD.items():
    romankeyList.append(key)
    romanvalueList.append(value)
print "Key List:",romankeyList
print "Value List:",romanvalueList

print

# make a dictionary from the two lists
print "Combining the two lists into a dictionary:"
romanD1 = dict(zip(romankeyList, romanvalueList))
print romanD1

# to save a Python object like a dictionary to a file
# and load it back intact you have to use the pickle module
import pickle
print "The original dictionary:"
print romanD1
file = open("roman1.dat", "w")
pickle.dump(romanD1, file)
file.close()
file = open("roman1.dat", "r")
romanD2 = pickle.load(file)
file.close()
print "Dictionary after pickle.dump() and pickle.load():"
print romanD2

print

# let's get rid of some duplicate words
str = "Senator Strom Thurmond dressed as as Tarzan"
print "\nOriginal string:"
print str
print "A list of the words in the string:"
wrdList1 = str.split()
print wrdList1

def uniqueList(anyList):
    """given a list, returns a unique list with the order retained"""
    # create an empty dictionary
    dic1 = {}
    # use a list comprehension statement and the unique feature of a dictionary
    return [dic1.setdefault(e,e) for e in anyList if e not in dic1]

# a call to the above function will retain the order of words
wrdList2 = uniqueList(wrdList1)
print "Convert unique list back to string (order retained):"
print " ".join(wrdList2)
jcmeyer 0 Light Poster

What if I wanted to store a dictionary in a sqlite database? I would imagine that I would use the pickle module similarly to how you have used it here. But, how would I go about doing that?

Editor's note:
Please make this a separate thread in the forum, otherwise it gets hidden too much.

playonlcd 0 Newbie Poster

Good summary of working with dictionaries.
But... :)
How you can extract an key from a dictionary of a dictionary?
Let's say we have the following dictionary:

{'AAA':{'KEY1':'text1', 'KEY2':'text2',  'KEY3:' 'text3', 'KEY4': 'text4'},
'BBB':{'BBB1':{'KEY1':'text1', 'KEY2':'text2',  'KEY3:' 'text3', 'KEY4': 'text4'},
         'BBB2':{'KEY1':'text1', 'KEY2':'text2',  'KEY3:' 'text3', 'KEY4': 'text4'},
         'BBB3':{'KEY1':'text1', 'KEY2':'text2',  'KEY3:' 'text3', 'KEY4': 'text4'}}}

How can i extract KEY1, KEY2 and KEY 4 from AAA and KEY3 KEY4 from BBB1, BBB2, BBB3 in BBB?
:)

Editor's note:
Please make this a separate thread in the forum, otherwise it gets hidden too much.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Note:
Use binary file modes "wb" and "rb" to make pickle work with Python2 and Python3 versions.

Babe1 -3 Newbie Poster

I'm trying to pick "a..z", "A..z", "space", "." and "," out of a list an putting them in another list? can you help?

Editor's note:
Please make this a separate thread in the forum, otherwise it gets hidden from view too much.

TrustyTony commented: Make new thread for your question, do not hijack threads. -3
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.