ActiveState Code

Recipe 573453: String representation of a dict (sorted by key)


I quite often find a need to create a 'key-value' pair representation of a dictionary as a string, mainly using generators and the .join method of string objects

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
def genkvs(d, keys, joiner):
    for key in keys:
        yield '%s%s%s' % (key, joiner, d[key])

def dictjoin(_dict, joiner, sep):
    keys = sorted(_dict.iterkeys())
    return sep.join(genkvs(_dict, keys, joiner))

def test_dictjoin():
    """This test function can be used for testing dictjoin with py.test of
    nosetests."""
    def dictjointest(_dict, expected):
        assert dictjoin(_dict, '=', '; ') == expected

    yield dictjointest, {}, ''
    yield dictjointest, dict(a=1), 'a=1'
    yield dictjointest, dict(a=1, b=2), 'a=1; b=2'

if __name__ == '__main__':
    # Simple demonstration
    print dictjoin(dict(a=1, b=2, c=3, d=4), ' = ', '; ')

Comments

  1. 1. At 1:34 p.m. on 30 jan 2009, MichaƂ Pecyna said:

    Hi!

    >>> dictjoin = lambda d,j='=',s='; ': s.join([j.join((str(k),str(v))) for k,v in d.iteritems()])
    >>> dictjoin(dict(a=1,b=2,c=3))
    'a=1; c=3; b=2'
    >>> dictjoin(dict(hello='world'),' ')
    'hello world'
    

    :P

Sign in to comment