Py学习  »  esquisilo  »  全部回复
回复总数  1
3 年前
回复了 esquisilo 创建的主题 » 如何在python中将一串键值转换为正确的dict?

如果你不想使用正则表达式,我想你可以这样做:

  1. 将字符串拆分为一个由冒号分隔的数组。
  2. 初始化字典
  3. 循环使用冒号分隔的字符串,按空格分隔,将最后一个元素称为下一个键,将其他元素称为最后一个键的条目。
  4. 然后对第一个元素(有一个项但没有项)和最后一个元素(有一个项但没有项)进行例外。

这里有一些代码

#1. Separate by colon
blah = 'address: 123 fake street city: new york state: new york    population:        500000'
colon_split = blah.split(":")
#Assuming string is always formatted...
# Key(ONE WORD): Entry, maybe multiple words KEY(ONE WORD): etc. etc. etc.
#Then the first element of the array above is automatically a key.

#Initialize your dictionary
Dictionary = {}

#3. Separate by space to find keys and populate the dict
#Since your entries are in series here, you'll have three kind of element.
#....Your first element will be just a key
#....The rest will be the entry for the previous key followed by a new key
#....Your last element will be just an entry

for i in range(len(colon_split)):
    if i==0:
        key = colon_split[i]
    elif i==len(colon_split)-1:
        entry = colon_split[i]
        Dictionary[key] = entry
    else:
        entry_array = colon_split[i].split(" ")[:-1]
        entry = " ".join(entry_array)
        #Put the current iteration's entry into the last iteration's key 
        Dictionary[key] = entry
        key = colon_split[i].split(" ")[-1]