Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 936
Mehar Avatar asked Dec 06 '25 12:12

Mehar


2 Answers

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()
}
like image 185
azro Avatar answered Dec 09 '25 01:12

azro


you are removing all the elements from your set at this line setItem.clear()

you can use a dictionary comprehension to convert your list elements to set:

dictionaryObj = {k: set(v) for k, v in dictionaryObj.items()}
like image 36
kederrac Avatar answered Dec 09 '25 02:12

kederrac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!