首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法使字典键看起来像我想要的那样

无法使字典键看起来像我想要的那样
EN

Stack Overflow用户
提问于 2012-08-30 10:48:23
回答 2查看 326关注 0票数 0

我需要我的字典关键字格式为'/ cat/‘,但我总是得到多个正斜杠。下面是我的代码:

代码语言:javascript
复制
 # Defining the Digraph method #
 def digraphs(s):
      dictionary = {}
      count = 0;
      while count <= len(s):
          string = s[count:count + 2]
          count += 1
          dictionary[string] = s.count(string)
      for entry in dictionary:
          dictionary['/' + entry + '/'] = dictionary[entry]
          del dictionary[entry]
      print(dictionary)
 #--End of the Digraph Method---#

下面是我的输出:

我这样做:

有向图(‘我的猫在帽子里’)

代码语言:javascript
复制
{'///in///': 1, '/// t///': 1, '/// c///': 1, '//s //': 1, '/my/': 1, '/n /': 1, '/e /': 1, '/ h/': 1, '////ha////': 1, '//////': 21, '/is/': 1, '///ca///': 1, '/he/': 1, '//th//': 1, '/t/': 3, '//at//': 2, '/t /': 1, '////y ////': 1, '/// i///': 2}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-08-30 10:54:27

在Python中,通常不应该在修改对象时遍历对象。不要修改你的字典,而是创建一个新的字典:

代码语言:javascript
复制
new_dict = {}

for entry in dictionary:
    new_dict['/' + entry + '/'] = dictionary[entry]

return new_dict

或者更简洁(Python 2.7及更高版本):

代码语言:javascript
复制
return {'/' + key + '/': val for key, val in dictionary.items()}

一个更好的方法是从一开始就跳过创建原始字典:

代码语言:javascript
复制
# Defining the Digraph method #
def digraphs(s):
    dictionary = {}

    for count in range(len(s)):
        string = s[count:count + 2]
        dictionary['/' + string + '/'] = s.count(string)

    return dictionary
#--End of the Digraph Method---#
票数 3
EN

Stack Overflow用户

发布于 2012-08-30 10:51:05

当循环遍历字典时,您会向字典中添加条目,因此您的新条目也会包含在循环中,并且会再次添加额外的斜杠。一种更好的方法是制作一个包含您想要的新关键字的新字典:

代码语言:javascript
复制
newDict = dict(('/' + key + '/', val) for key, val in oldDict.iteritems())

正如@Blender指出的,如果你使用的是Python 3,你也可以使用字典理解:

代码语言:javascript
复制
{'/'+key+'/': val for key, val in oldDict.items()}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12189184

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档