如何将字符串空格分隔的键,唯一字的值对转换为字典 [英] How to transform string of space-separated key,value pairs of unique words into a dict

查看:576
本文介绍了如何将字符串空格分隔的键,唯一字的值对转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,其中的单词用空格分隔(所有单词都是唯一的,没有重复)。我将此字符串转换为列表:

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 。这些对成为元组/对的列表 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆