【问题标题】:How to iterate over a dictionary to make new for loop for the remaining elements?如何遍历字典以为剩余元素创建新的 for 循环?
【发布时间】:2014-08-20 14:12:21
【问题描述】:

我正在尝试根据我现有的词典制作一本新词典。

`dict1 = {'A':{}, 'B':{}, 'C':{}, 'D':{}, 'E':{}}
 for key, val in dict1.iteritems():
    mytest = key
    newConditionFlag = getSummary(mytest)
    if newConditionFlag == 1:
        make dict2`

其中getSummary函数如下:

`def getSummary(mytest):
    newConditionFlag==0
    bVal = mytest.CanClose()
    if bVal == True:
        pass
    else:
        newConditionFlag=1
    return newConditionFlag`

如果 B 的 newConditionFlag == 1,那么我的 dict2 应该是

dict2 = 'C':{}, 'D':{}, 'E':{}}。 同样,如果 C 的 newConditionFlag == 1,

dict2 = 'D':{}, 'E':{}}。 我该怎么做?

我知道,如果我们想访问剩余的值,我们要做的就是一个简单的条件

`l = [1,2,3,4,5]
for i,j in zip(l, l[2:]):
    print j`

但是在字典的情况下应该怎么做呢?如果我们以同样的方式尝试它会得到TypeError: unhashable type

【问题讨论】:

  • “从那时起”的概念没有意义——字典是无序的。你想达到什么目的。
  • @jonrsharpe 字典中提到的字典是无序的,您可能想使用:docs.python.org/2.7/library/… 但很难判断它是否对您的工作有任何好处
  • @jonrsharpe 我已经编辑了代码,希望对您有所帮助

标签: python loops for-loop dictionary


【解决方案1】:

这可能有意义的唯一方法是首先将字典转换为列表。对列表进行处理,然后转换回字典。

l = sorted(dict1.items())
# do your thing
dict1 = dict(l)

【讨论】:

    猜你喜欢
    • 2016-01-11
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 2013-02-20
    • 2011-03-18
    相关资源
    最近更新 更多