Powered by Ajaxy
Digg StumbleUpon LinkedIn YouTube Flickr Facebook Twitter RSS Reset

Python: How to create a dictionary and fetch value by key

# Define a dictionary
con_str = {"host":"127.0.0.1", "database":"mysql", "user":"root", "pwd":"mysql"}
print 'Entries: ', con_str
print 'Password:'

Python: How to reference dictionary in print function

dict={"num":1, "val":"symponium"}
print "%(num)d %(val)s" % dict

Python: How to Use variable as a key

even  =   [2, 4, 6, 8]
odd=   [1, 3, 5, 7, 9]
dict={'even':even, 'odd':odd}
# convet to string
print str(dict)
print repr(dict)

Python: How to Add new entry to a dictionary

# Create a dictionary
myDict = {'Font': 12, 'Style': Bold', 'Color': 'black'}
print myDict
# Change the entry "color"
myDict['Color'] = ['255', '0'

Python: list the dictionary’s keys

dict = {1: 'ABC', 2: 'abc', 3: 'AbC'}
print dict
# print the keys
print dict.keys()

Python: Comparing Dictionaries

even  =   [2, 4, 6, 8]
odd=   [1, 3, 5, 7, 9]
d1 = {'Name': 'even', 'Values':even}
d2 = {'Name': 'odd', 'Values':odd}
print d1==d2 # false
print d1

Python: check to see whether a key exists in a dictionary.

params = {'Font': 12, 'Style': 'Bold', 'Color': [128, 0, 255]}
print params.has_key('Font')      # True
print params.has_key('Resolution')  # False

Python: Looping over a dictionary

dict = {'x': 1, 'y': 2, 'z': 3}
for key in dict:
    print key, '=>', dict[key]

Python: Using For loop through the dictionary keys

# Define a dictionary
params = {'Font': 12, 'Style': 'Bold', 'Color': [255, 0, 255]}
for key in params.keys():
    print key,' ', params[key]
[/pyt

Python: create a shallow copy of a dictionary

# Define a dictionary
myDict = {'Font': 12, 'Style': 'Bold', 'Color': [255, 255, 255]}
# create a shallow copy 
myDict2 = myDict.copy()
myDict2['Fo

Python: sort a dictionary’s keys

leaders = {'Python':  'Guido van Rossum',
          'Perl':    'Larry Wall',
          'Tcl':     'John Ousterhout' }
sortedKeys=leaders.keys()
pri

Python-dictionary: get a value by using a key or a default value (if the key doesn’t exist)

# Define a dictionary
con_str = {"host":"127.0.0.1",
           "database":"mysql",
           "user":"root",
           "pwd":"mysql"}
print con_s

Python: merge the key-value pairs of two dictionaries

even  =   [2, 4, 6, 8]
odd=   [1, 3, 5, 7, 9]
dict={'even':even, 'odd':odd}
params = {'Font': 12, 'Style': 'Bras', 'Color': [255, 0, 255]}
# Combin

Python-dictionary: Getting a Value by Using a Key

# Define a dictionary
con_str = {"host":"127.0.0.1",
           "database":"mysql",
           "user":"root",
           "pwd":"mysql"}
print con_s

Python-dictionary: Get value by key

# Définition d'un dictionnaire
con_str = {"host":"127.0.0.1",
           "database":"mysql",
           "user":"root",
           "pwd":"mysql"}
pr