# Python dictionary basics operations

data={'Name':'Viv','id':'yom439','Major':'CS','Degree':'MS'}

print (data['Name'])
print (data['Major'])

print ('\n Before adding new key to dictionary');
print("\n",data)

data['Sem']=3 # Adding new key to dictionary

print ('\n After adding new key to dictionary');
print("\n",data)

#Notes: data.clear() clears all entries in dictionary
#Notes: del data; deletes dictionary

# Converting lists into Dictionaries
print '\n Converting lists into Dictionaries'

states={}
numofstates=int(raw_input('\n Enter number of states'))
for i in range(0, numofstates):
statename=raw_input('\n Enter the state:')
states[statename]={}

capitals={}
for j in range(0,numofstates):
capitalname=raw_input('\n Enter the capital name:')
capitals[capitalname]={}

# Step 1: Convert the lists which you want to make dictionary into tuple format using zip()

state_capital=zip(states,capitals)
print '\n'
print(state_capital)

# Step 2: Now convert this tuple into dictionary using dict()

states_and_capitals=dict(state_capital)
print '\n'
print(states_and_capitals)

0 Comments:

Post a Comment



Newer Post Older Post Home