简体   繁体   中英

How to convert a tuple of string and tuples into a list of string and lists

I have a created a dictionary key which is a tuple of string & tuples. The typical key looks like

("string1", ('string2','string3', 'string4'), (int1, int2, int3) )

I need to now copy the key to a list to modify string2 & int2 and reconvert it back into a new tuple which will then serve as a dictionary key to a new entry.

When I try to make a list from this tuple using

listKey = [list(i) for i in key]

I get an output that looks like

[['s','t','r','i','n','g','1'],['string2','string3','string4'],[int1, int2, int3]]

  1. How can I retain the 'string1' as it was in the original dictionary key when I convert it into a list?
  2. How to retain 'string1' when the modified list is converted back to tuple?

You may only need to call list(i) If not, you could try (("string1"),('string2', 'string3', ...) ...)

Or you could use this:

listKey = [i if isinstance(i, str) else list(i) for i in key]

Hope this helps solve your problem.

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