Python gets string (key + value) from Python Dictionary

I have a dictionary structure. For instance:

dict = {key1 : value1 ,key2 : value2} 

What I want is a string that combines the key and the value

Required 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()) 
+6
source share
3 answers

A list key values str s,

 >>> d = {'key1': 'value1', 'key2': 'value2'} >>> ['{}_{}'.format(k,v) for k,v in d.iteritems()] ['key2_value2', 'key1_value1'] 

Or, if you need one row of all key-value pairs,

 >>> ', '.join(['{}_{}'.format(k,v) for k,v in d.iteritems()]) 'key2_value2, key1_value1' 

EDIT:

Perhaps 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 might also want to break after print ing - it's hard to know exactly what that means.

+15
source

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()]) 
+3
source
 def checkCommonNodes(id, rs): k,v = id.split('_') for d in rs: if d.get(k) == v: return id retun None 
0
source

Source: https://habr.com/ru/post/948676/


All Articles