Question

I have a following dictionary:

{'key1': 'list1', 'key2': 'list2', and so on}

I want to print it, and output it into a csv file in the following order:

key1 list1_element_1
key1 list1_element_2
key1 list1_element_n
key2 list2_element_1
key2 list2_element_n

How do I do that? This may(quite possibly) be an elementary question, however I could not find the answer. Thanks.

Was it helpful?

Solution

Assuming your values are lists/tuples you can do the following and that you are using OrderedDict

dictionary = {'key1': ['value1', 'value2', 'value3'], 'key2': ['value1', 'value2']}

for key, values in dictionary.items():
   for value in values:
       print '{} {}'.format(key, value)

If you are using a normal dict (i.e. not an OrderedDict) then you need to sort first:

dictionary = {'key1': ['value1', 'value2', 'value3'], 'key2': ['value1', 'value2']}

for key, values in sorted(dictionary.items()):
   for value in values:
       print '{} {}'.format(key, value)

The code above only prints the values as you had in your example output. You can write them to a csv file or do whatever you desire.

The output for the second example would be:

key1 value1
key1 value2
key1 value3
key2 value1
key2 value2

OTHER TIPS

There are two concepts related to your problem here.

  1. How to store a multidictionary
  2. How to store an ordered dictionary

For the first problem, you simply store a list of values for each key instead of one single value For the second problem, you can use the OrderedDict from the collections library

import collections

def add_value(d, key, value):
    # get a list of values by key or set a default empty list
    lst = d.setdefault(key, list())
    lst.append(value)

def print_dict(d):
    for key, values in d.items():
        for single in values:
            print "{} {}".format(key, single)


d = collections.OrderedDict()
add_value(d, "key1", "value1")
add_value(d, "key1", "value2")
add_value(d, "key1", "valueN")
add_value(d, "key2", "value1")
add_value(d, "key2", "value2")
print_dict(d)

First, a key cannot have more than one value associated to it.

Assuming a single key/value pair, sample code would be

info = {
"key1":"xyz",
"key4":"anotherrandom",
"key2":"abaadfas",
"key3":"random"
      }
for key in sorted(info):
        print "key: {} and value: {}".format(key,info[key])

If you want to associate more than value to a key, you could use a list.

info = {
"key1": [1,2,3],
"key4": [1],
"key2": [5,7,8],
"key3": [0,11,7,8]

}
for key in sorted(info):
    print "key: {} and value: {}".format(key,info[key])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top