Pacific-Design.com

    
Home Index

1. Python

2. 02 Dictionary

Python / 02 Dictionary /

Python Dictionary Transformation

#!/usr/bin/python
import operator
#-------------------------------------------------#
dict =  {   
            "Agoura Hills"  : 20745,
            "Calabasas"     : 24176,
            "Los Angeles"   : 3976000,
            "Malibu"        : 12879,
            "Santa Monica"  : 92478  
        }   

city = dict.get("Agoura Hills", 0)
print(city)

# assign value
dict["Calabasas"] = 25000

city = dict.get("Calabasas", 0)
print(city)


#-------------------------------------------------#
print("\n------  Display Items ---------")
for k, v in dict.items():
    print "%s: %s" % (k, v)

print("\n------  Display Keys ----------")
for key in dict.iterkeys():
    print(key)

print("\n------  Display Values --------")
for value in dict.itervalues():
    print(value)

print("\n------- Keys Key Value --------")
for key, value in dict.iteritems():
    print(key, value)

print("\n------- Sort Dictionary -------")
sorted_x = sorted(dict.items(), key=operator.itemgetter(1))
for k,v in sorted_x:
    print k, v
20745 25000 ------ Display Items --------- Malibu: 12879 Calabasas: 25000 Santa Monica: 92478 Los Angeles: 3976000 Agoura Hills: 20745 ------ Display Keys ---------- Malibu Calabasas Santa Monica Los Angeles Agoura Hills ------ Display Values -------- 12879 25000 92478 3976000 20745 ------- Keys Key Value -------- ('Malibu', 12879) ('Calabasas', 25000) ('Santa Monica', 92478) ('Los Angeles', 3976000) ('Agoura Hills', 20745) ------- Sort Dictionary ------- Malibu 12879 Agoura Hills 20745 Calabasas 25000 Santa Monica 92478 Los Angeles 3976000