简体   繁体   中英

How to differentiate the dict key and values based on delimiters

I have a dict of type x={'a':'1','b':'2','c;0':'a1;b1;b2;b3;b4','c;1':'a2;b2;b3;b4;b5;b6'}

i am writing program like this

for key,values in x.iteritems():
   if key.split(";") is True:
      print key,value
   else:
      print key,value

its not working properly.

in output what i want on execution of

if key.split(";") is False
   print key,values

output should be

a 1
b 2

in output what i want on execution of

if key.split(";") is True
   print key,values

output should be

c;0  a1;b1;b2;b3;b4,
c;1  a2;b2;b3;b4;b5;b6

I think you don't really need any if / else condition since you're printing key/value pairs for both cases:

>>> for k, v in x.iteritems():
...     print k, v
a 1
b 2
c;1 a2;b2;b3;b4;b5;b6
c;0 a1;b1;b2;b3;b4

Looking at the output you provided, the only difference I see is that your example is ordered. If that's what you're looking for then, you can use sorted like this:

>>> for k, v in sorted(x.iteritems()):
...     print k, v
a 1
b 2
c;0 a1;b1;b2;b3;b4
c;1 a2;b2;b3;b4;b5;b6

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM