Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python getting a string (key + value) from Python Dictionary

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())
like image 672
Peter Avatar asked Jul 04 '13 06:07

Peter


2 Answers

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.

like image 144
Jared Avatar answered Nov 03 '22 23:11

Jared


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()])
like image 3
gramonov Avatar answered Nov 03 '22 23:11

gramonov