Python ->
Python. Number of ways to explore dictionary content

This example we will examin a number of ways to explore dictionary content. The source data of the example represents list of dictionaries, and by the way is a valid json string.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
printing dictionaries content in a number of possible ways
"""

# init list of dictionaries (actually this is valid json string)
data = [
   {"city": "London", "code": "LN", "population": 8674000},
   {"city": "New York", "code": "NY", "population": 8406000},
   {"city": "Paris", "code": "PAR", "population": 2244000}
   ]
# what we have ?
print type(data)
print type(data[0])
print ('')

# print all data
print ('# Print 1. Raw dictionary data')

# print all dictionaries in the list
for my_dict in data:
  print my_dict
  print ('KEYS: {0}'.format(my_dict.keys()))
  print ('VALUES: {0}'.format(my_dict.values()))
  # print items
  for item in my_dict:
   print item

# different ways to print Key-Value pairs of every dictionary

print ('')
print ('# Print 2. Key-Value pairs')

for my_dict in data:
  for key in my_dict.keys():
   print ("{0}: {1}".format(key, my_dict[key]))

print ('')
print ('# Print 3. Key-Value pairs')

for my_dict in data:
  for key, value in my_dict.items():
   print str(key) + " => " + str(value)

print ('')
print ('# Print 4. Key-Value pairs')

for my_dict in data:
  for kv in my_dict.items():
   print kv[0],'\t', kv[1]




sqlexamples.info