Goutam
Goutam

Reputation: 1367

how to convert a set in python into a dictionary

I am new to python and trying to convert a Set into a Dictionary. I am struggling to find a way to make this possible. Any inputs are highly appreciated. Thanks.

Input : {'1438789225', '1438789230'}

Output : {'1438789225':1, '1438789230':2}

Upvotes: 1

Views: 3915

Answers (4)

Carcigenicate
Carcigenicate

Reputation: 45736

My Python is pretty rusty, but this should do it:

def indexedDict(oldSet):
    dic = {}
    for elem,n in zip(oldSet, range(len(oldSet)):
        dic[elem] = n

    return dic

If I wrote anything illegal, tell me and I'll fix it. I don't have an interpreter handy.

Basically, I'm just zipping the list with a range object (basically a continuous list of numbers, but more efficient), then using the resulting tuples. Id got with Tiger's answer, this is basically a more naive version of his.

Upvotes: 0

Agustín Lado
Agustín Lado

Reputation: 1095

My one-liner:

output = dict(zip(input_set, range(1, len(s) + 1)))

zip mixes two lists (or sets) element by element (l1[0] + l2[0] + l1[1] + l2[1] + ...).

We're feeding it two things:

  • the input_set
  • a list from 1 to the length of the set + 1 (since you specified you wanted to count from 1 onwards, not from 0)

The output is a list of tuples like [('1438789225', 1), ('1438789230', 2)] which can be turned into a dict simply by feeding it to the dict constructor... dict.

But like TigerhawkT3 said, I can hardly find a use for such a dictionary. But if you have your motives there you have another way of doing it. If you take away anything from this post let it be the existence of zip.

Upvotes: 2

Mattia Primavera
Mattia Primavera

Reputation: 16

an easy way of doing this is by iterating on the set, and populating the result dictionary element by element, using a counter as dictionary key:

def setToIndexedDict(s):
    counter = 1
    result = dict()

    for element in s:
        result[element] = counter #adding new element to dictionary
        counter += 1 #incrementing dictionary key

    return result

Upvotes: 0

TigerhawkT3
TigerhawkT3

Reputation: 49318

Use enumerate() to generate a value starting from 0 and counting upward for each item in the dictionary, and then assign it in a comprehension:

input_set = {'1438789225', '1438789230'}
output_dict = {item:val for val,item in enumerate(input_set)}

Or a traditional loop:

output_dict = {}
for val,item in enumerate(input_set):
    output_dict[item] = val

If you want it to start from 1 instead of 0, use item:val+1 for the first snippet and output_dict[item] = val+1 for the second snippet.

That said, this dictionary would be pretty much the same as a list:

output = list(input_set)

Upvotes: 4

Related Questions