Home > Net >  How can I create names of dict's from a sequense of tuples of strings?
How can I create names of dict's from a sequense of tuples of strings?

Time:08-07

I have: paare = {('F1', 'F2'), ('F2', 'F3'), ...} and want create a list of dict's like:

[F1F2 = dict(a='F1', b='F2'), F2F3 = dict(a='F2', b='F3'), ...] nothing must be sorted;

for k, v in paare: => ValueError: too many values to unpack (expected 2) [that's not my main question]

When I compose the name of the dict's like dnam = 'F1F2' and then try to use this composed string "dnam" to define a new dict like pnam = {} then it is called 'pnam' and not 'F1F2'.

Is there a nice way to solve the problem?

CodePudding user response:

You could use a dict comprehension like so (you can't have a key value mapping with a list):

>>> paare = {('F1', 'F2'), ('F2', 'F3')}
>>> pnam = {f'{a}{b}': {'a': a, 'b': b} for a, b in paare}
>>> pnam
{'F1F2': {'a': 'F1', 'b': 'F2'}, 'F2F3': {'a': 'F2', 'b': 'F3'}}

CodePudding user response:

IIUC, You can use list comprehension.

s = {('F1', 'F2'), ('F2', 'F3'), ('F3', 'F4')}
res = [{'a':tpl[0], 'b':tpl[1]} for tpl in s]
print(res)
# Or as 'Dict' of 'Dicts'
res2 = {''.join(tpl) : {'a':tpl[0], 'b':tpl[1]} for tpl in s}
# Or 
# res2 = {''.join(tpl) : dict(a=tpl[0], b=tpl[1]) for tpl in s}
print(res2)

# res
[{'a': 'F1', 'b': 'F2'}, {'a': 'F2', 'b': 'F3'}, {'a': 'F3', 'b': 'F4'}]

# res2
{
    'F1F2': {'a': 'F1', 'b': 'F2'}
    'F2F3': {'a': 'F2', 'b': 'F3'},
    'F3F4': {'a': 'F3', 'b': 'F4'},
}
  • Related