Is there a way to make a dictionary value equivalent to set element in python?

Mehar Fatima Khan :

I am new to Python and I am using Python 3.7. So, I am trying to make my dictionary value equal to set i.e., dictionaryNew[kId] = setItem. So basically I want each kId (key) to have a corresponding row of set as its value. I am using set because I don't want duplicate values in the row.

This is a piece from my code below:

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)

When I print setItem, then the result is printed correctly.

Output of setItem:

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

But when I print dictionaryNew, the result is like the one displayed below.

Output of dictionaryNew:

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

I don't want the output to be like this. Instead, I want the dictionary to have a row of set with its values. But this is just printing empty set when I try to print dictionaryNew. So what should I do to solve this issue?

azro :

You're using the same setItem instance all along, if you remove setItem.clear() you'll see that every key points to the same value.

You may create a new set() at each iteration

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

Using dict-comprehension this it equivalent to

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=319206&siteId=1