有一个奇怪的字符串表示形式,例如
“ key1:value1:key2:value2:key3:value3 ... keyn:valuen”
我需要创建一个字典,当您有逗号时,这很容易解决,但是这里只有冒号,您必须每隔一个冒号就分割一次字符串。带有循环或类似代码的代码看起来很丑陋,所以我想知道您是否可以在oneliner方面为我提供帮助。
答案 0 :(得分:7)
您可以在冒号上进行分割,get an iterator放在标记上,zip
迭代器本身。这样可以很好地将键和值配对:
s = 'key1:value1:key2:value2:key3:value3:keyn:valuen'
it = iter(s.split(':'))
dict(zip(it, it))
# {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'keyn': 'valuen'}
答案 1 :(得分:1)
如果您对iter不满意(以及我认为更优越的schwobaseggls解决方案),则可以使用几乎相同的方式使用压缩的列表切片:
s = 'key1:value1:key2:value2:key3:value3:keyn:valuen'
splitted = s.split(':')
# even_elements = splitted[::2] - take every 2nd starting at 0th index
# odd_elements = splitted[1::2] - take every 2nd startIng at 1st index
k = {k:v for k,v in zip(splitted[::2],splitted [1::2]) }
print(k)
输出:
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'keyn': 'valuen'}
或者,您手动创建字典:
s = 'key1:value1:key2:value2:key3:value3:keyn:valuen'
splitted = s.split(':')
d ={}
# this generates 2-slices from the list and puts them into your dict
for k,v in (splitted[i:i+2] for i in range(0,len(splitted),2)):
d[k] = v
# or d = { k:v for k, v in (splitted[i:i+2] for i in range(0,len(splitted),2) )}
# or d = dict(splitted[i:i+2] for i in range(0,len(splitted),2) )
print(d)
输出:
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'keyn': 'valuen'}