Question

I am having an issue formatting my dictionary right now in key value pairs.

x = [('the', 709),  ('of',342), ('to',305)]

does anyone know how I can get this to show

the:709
of:342
to:305

I just cannot figure out the split.

Was it helpful?

Solution

x is a list, not a dictionary. You can iterate over list items and unpack tuples this way:

>>> x = [('the', 709),  ('of',342), ('to',305)]
>>> for a, b in x:
...     print '%s:%s' % (a, b)
... 
the:709
of:342
to:305

If you want to make a dictionary from x, just pass it to dict():

>>> d = dict(x)
>>> d
{'of': 342, 'the': 709, 'to': 305}
>>> for a, b in d.iteritems():
...     print '%s:%s' % (a, b)
... 
of:342
the:709
to:305

Note that dictionaries are unordered collections - don't expect items in order that you have inside x.

OTHER TIPS

If you're using a dictionary

x = {"the": 709, "of": 342, "to": 305}
for key, value in x.iteritems():
    print key + ": " + str(value)

If you're using a list of tuples:

x = [('the', 709),  ('of' ,342), ('to', 305)]
for a, b in x:
    print a + ": " + str(b)

Unless you need them in order, you should use a dictionary for this kind of thing (Python dictionaries are unordered).

If you want a dictionary, it should look like:

x = {"the": 709, "of": 342, "to": 305}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top