Home > Back-end >  Extracting a dictionary into a set of tuples
Extracting a dictionary into a set of tuples

Time:11-21

Giving this dictionary:

 d = {'x': '999999999',
'y': ['888888888', '333333333'],
'z': '666666666',
'p': ['0000000', '11111111', '22222222'] }

is it possible to make a set of tuples ?

The output should be {( x, 999999999),(y,888888888, 333333333),...}

I tried this : x_set = {(k, v) for k, values in d.items() for v in values}

CodePudding user response:

x_set = set()
for k, v in d.items():
    items = [k]
    if(type(v) == list):
        items.extend(v)
    else:
        items.append(v)
    x_set.add(tuple(items))

Check if the dictionary element is a list or not so you know whether to iterate through the element or simply append it.

CodePudding user response:

You could construct a set of tuples with cases depending on whether the dictionary values are lists or not.

d = {'x': '999999999',
'y': ['888888888', '333333333'],
'z': '666666666',
'p': ['0000000', '11111111', '22222222'] }

tuple_set = set(tuple([k]   list(map(int, v)) if isinstance(v,list) else [k, int(v)]) for k,v in d.items())
  • Related