I have dictionary structure. For example:
dict = {key1 : value1 ,key2 : value2}
What I want is the string which combines the key and the value
Needed string -->> key1_value1 , key2_value2
Any Pythonic way to get this will help.
Thanks
def checkCommonNodes( id  , rs):
     for r in rs:
         for key , value in r.iteritems():
             kv = key+"_"+value
             if kv == id:
                 print "".join('{}_{}'.format(k,v) for k,v in r.iteritems())
                A list of key-value strs,
>>> d = {'key1': 'value1', 'key2': 'value2'}
>>> ['{}_{}'.format(k,v) for k,v in d.iteritems()]
['key2_value2', 'key1_value1']
Or if you want a single string of all key-value pairs,
>>> ', '.join(['{}_{}'.format(k,v) for k,v in d.iteritems()])
'key2_value2, key1_value1'
EDIT:
Maybe you are looking for something like this,
def checkCommonNodes(id, rs):
    id_key, id_value = id.split('_')
    for r in rs:
        try:
            if r[id_key] == id_value:
                print "".join('{}_{}'.format(k,v) for k,v in r.iteritems())
        except KeyError:
            continue
You may also be wanting to break after printing - hard to know exactly what this is for.
Assuming Python 2.x, I would use something like this
dict = {'key1': 'value1', 'key2': 'value2'}
str = ''.join(['%s_%s' % (k,v) for k,v in dict.iteritems()])
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With