List - Dictionary - Tuples: Solutions

List

Problem 1

Consider the list:


In [ ]:
oldList = [[1,2,3],[4,5,6]]

Use operations on lists to manipulate oldList and create the list [[1,2],[4,6]]

Solution 1


In [ ]:
a = oldList[0]
print a
a.remove(3)
b = oldList[1]
print b
b.remove(5)
newList = []
newList.append(a)
print newList
newList = newList.append(b)
print newList

Tuples

Problem 2

Consider the tuple:


In [ ]:
julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia")

Use tuple operations to manipulate the above tuple to get a new tuple:


In [ ]:
("Julia", "Roberts", 1967, "Eat Pray Love", 2010, "Actress", "Atlanta, Georgia")

Solution 2


In [ ]:
julia = julia[:3] + ("Eat Pray Love", 2010) + julia[5:]
print julia

Dictionary

Problem 3

Consider the following dictionary


In [ ]:
ab = {'met_opt': '3',
      'met_grid_type': 'A',
      'do_timinterp_met': 'F',
      'mrnum_in': '1',
      'met_filnam_list': 'jan2004.list',
      'do_read_met_list': 'T',
      'do_cycle_met': 'F',
      'gwet_opt': '1',
      'mdt': '10800.0'
     }
  • Print the value associated with the key 'mdt'
  • Print the length of the dictionary
  • Add to the dictionary another key 'met_infile_num' with the corresponding value '16'
  • Print the length of the dictionary
  • Write a loop to only print all the keys
  • Wrute a loop to only print all the values
  • Write a loop to print on the same line each key and its correcponding value

Solution 3


In [ ]:
print 'mdt = ', ab['mdt']

print len(ab)

ab['met_infile_num'] = '16'

print len(ab)

# Print the keys
for key in ab:
    print key

for key in ab.iterkeys():
    print key

# Print the values
for val in ab.itervalues():
    print val

# Print key & value
for key, val in ab.items():
    print key, val
    
for key in d:
    print key, d[key]