【问题标题】:Is there a way to make a dictionary value equivalent to set element in python?有没有办法使字典值等同于 python 中的 set 元素?
【发布时间】:2020-06-29 09:38:21
【问题描述】:

我是 Python 新手,我正在使用 Python 3.7。所以,我试图让我的字典值等于集合,即dictionaryNew[kId] = setItem。所以基本上我希望每个kId(键)都有一个对应的设置行作为它的值。我使用 set 是因为 我不希望行中有重复值。

这是我下面代码中的一段:

setItem = set()
dictionaryNew = {}

for kId, kVals in dictionaryObj.items():
    for index in kVals:   
        if (index is not None):
            yourVal = 0
            yourVal = yourVal + int(index[10])
            setItem.add(str(yourVal))
            print(setItem) #the output for this is correct

    dictionaryNew[kId] = setItem
    setItem.clear()

print(dictionaryNew)

当我打印setItem 时,结果打印正确。

setItem的输出:

{'658', '766', '483', '262', '365', '779', '608', '324', '810', '701', '208'}

但是当我打印dictionaryNew时,结果就像下面显示的那样。

dictionaryNew的输出:

{'12': set(), '13': set(), '17': set(), '15': set(), '18': set(), '10': set(), '11': set(), '14': set(), '16': set(), '19': set()}

我不希望输出是这样的。相反,我希望字典有一行带有其值的集合。但这只是在我尝试打印dictionaryNew 时打印空集。那么我应该怎么做才能解决这个问题呢?

【问题讨论】:

  • 你能分享dictionaryObj结构吗?我不确定它是什么
  • 为什么:youvalue + 0 每次?
  • dictionaryObj 有键:值对。所以基本上它有一个字符串作为键和一组字符串作为值。另外,我每次都使用 0,因为索引 [10] 处有增量编码。所以为了解码,我使用了这个公式。

标签: python python-3.x dictionary set


【解决方案1】:

您一直在使用相同的setItem 实例,如果您删除setItem.clear(),您会看到每个键都指向相同的值。

您可以在每次迭代时创建一个新的set()

dictionaryNew = {}
for kId, kVals in dictionaryObj.items():
    setItem = set()
    for index in kVals:   
        if index is not None:
            setItem.add(str(int(index[10]))) # the temp sum with 0 is useless

    dictionaryNew[kId] = setItem

使用 dict-comprehension 这相当于

dictionaryNew = {
    kId: {str(int(index[10])) for index in kVals if index is not None}
    for kId, kVals in dictionaryObj.items()
}

【讨论】:

  • 非常感谢!这解决了这个问题。我没有看到那样的。
  • @MeharFatimaKhan 不客气,你能举个例子说明 dictionaryObj 是什么吗?也许我可以写得更简单
  • 这是dictionarObj的结构示例。一个字符串作为键,一组字符串作为值。 '723':['1979','4225','780','7264'],'752':['6060','758','93','749'],'712':[' 345', '59', '11684', '2006'], '771': ['13770', '1148', '15198', '15184']
  • @MeharFatimaKhan 我不明白您尝试使用 index[10] 访问的内容,因为此时 index 只是一个字符
【解决方案2】:

您正在删除 set 在这一行 setItem.clear() 中的所有元素

您可以使用字典推导将列表元素转换为集合:

dictionaryObj = {k: set(v) for k, v in dictionaryObj.items()}

【讨论】:

  • 谢谢。我会试试这个。
猜你喜欢
  • 2019-06-06
  • 2014-05-29
  • 1970-01-01
  • 2020-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多