Saturday, October 31, 2009

Slicing a Dictionary










Slicing a Dictionary






year = {1:'January', 2:'February', 3:'March',
4:'April',\
5:'May', 6:'June', 7:'July', 8:'August',\
9:'September', 10:'October', 11:'November',\
12:'December'}

months = year.keys()
months.sort()
halfCount = len(months)/2
half = months[0:halfCount]
firstHalf = {}
for x in half:
firstHalf[x] = year[x]




There is no specific method to get a slice of a dictionary; however, this will be a common task that deserves some attention. The best way to slice out a subset of a dictionary is to first get the list of keys using the keys method. From the full list of keys, create a subset of that list through slicing or whatever means are necessary.


Once you have a specific subset of keys in the directory, you can pull out the values from the original dictionary and add them to a new dictionary.


If you want to keep the original dictionary intact, use the get method to pull out the value. However, if you want the value and keys removed from the original dictionary, use the pop method.


year = {1:'January', 2:'February', 3:'March',
4:'April',\
5:'May', 6:'June', 7:'July', 8:'August',\
9:'September', 10:'October', 11:'November',\
12:'December'}

print year

#Get list of keys
months = year.keys()

#Create subset of keys
months.sort()
halfCount = len(months)/2
half = months[0:halfCount]

#Create new dictionary from subset of keys
firstHalf = {}
for x in half:
firstHalf[x] = year[x]

print firstHalf


sub_dict.py


{1: 'January', 2: 'February', 3: 'March', 4:
'April', 5: 'May', 6: 'June', 7: 'July',
8: 'August', 9: 'September', 10: 'October',
11: 'November', 12: 'December'}

{1: 'January', 2: 'February', 3: 'March',
4: 'April', 5: 'May', 6: 'June'}


Output of sub_dict.py












No comments:

Post a Comment