如何将空格分隔的键、值对的字符串转换为字典 [英] How to transform string of space-separated key,value pairs of unique words into a dict
问题描述
我有一个字符串,其中的单词由空格分隔(所有单词都是唯一的,没有重复).我把这个字符串变成列表:
I've got a string with words that are separated by spaces (all words are unique, no duplicates). I turn this string into list:
s = "#one cat #two dogs #three birds"
out = s.split()
并计算创建了多少个值:
And count how many values are created:
print len(out) # Says 192
然后我尝试从列表中删除所有内容:
Then I try to delete everything from the list:
for x in out:
out.remove(x)
然后再数:
print len(out) # Says 96
谁能解释一下为什么它说的是 96 而不是 0?
Can someone explain please why it says 96 instead of 0?
更多信息
每行以#"开头,实际上是一对以空格分隔的单词:单词对中的第一个是键,第二个是值.
Each line starts with '#' and is in fact a space-separated pair of words: the first in the pair is the key and second is the value.
所以,我正在做的是:
for x in out:
if '#' in x:
ind = out.index(x) # Get current index
nextValue = out[ind+1] # Get next value
myDictionary[x] = nextValue
out.remove(nextValue)
out.remove(x)
问题是我无法将所有键值对移动到字典中,因为我只遍历 96 个项目.
The problem is I cannot move all key,value-pairs into a dictionary since I only iterate through 96 items.
推荐答案
我想你真的想要这样的:
I think you actually want something like this:
s = '#one cat #two dogs #three birds'
out = s.split()
entries = dict([(x, y) for x, y in zip(out[::2], out[1::2])])
这段代码是做什么的?让我们分解一下.首先,我们像您一样将 s
用空格分割成 out
.
What is this code doing? Let's break it down. First, we split s
by whitespace into out
as you had.
接下来我们遍历 out
中的对,称它们为x, y
".这些对成为元组/对的list
.dict()
接受大小为两个元组的列表,并将它们视为 key, val
.
Next we iterate over the pairs in out
, calling them "x, y
". Those pairs become a list
of tuple/pairs. dict()
accepts a list of size two tuples and treats them as key, val
.
这是我尝试后得到的结果:
Here's what I get when I tried it:
$ cat tryme.py
s = '#one cat #two dogs #three birds'
out = s.split()
entries = dict([(x, y) for x, y in zip(out[::2], out[1::2])])
from pprint import pprint
pprint(entries)
$ python tryme.py
{'#one': 'cat', '#three': 'birds', '#two': 'dogs'}
这篇关于如何将空格分隔的键、值对的字符串转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!