Welcome, guest | Sign In | My Account | Store | Cart

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, 21 lines
 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), ' = ', '; ')

1 comment

MichaƂ Pecyna 15 years, 2 months ago  # | flag

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

Created by Jacob Oscarson on Mon, 16 Jun 2008 (PSF)
Python recipes (4591)
Jacob Oscarson's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks