Home > Net >  reorganize a list of tuples
reorganize a list of tuples

Time:11-27

I have a list of tuple which contains packages and dependencies as follow:

list_packages_dep = [(['six'], 'absl-py'), (['html5lib', 'six'], 'bleach'), (['args'], 'clint'),
(['discord.py'], 'discord'), (['aiohttp'], 'discord.py'), 
(['click', 'itsdangerous', 'Jinja2', 'Werkzeug'], 'Flask'), 
(['importlib-metadata'], 'jsonpickle'), (['importlib-metadata'], 'Markdown'), 
(['six'], 'protobuf'), (['comtypes', 'pypiwin32', 'pywin32'], 'pyttsx3'), 
(['certifi', 'chardet', 'idna', 'urllib3'], 'requests')]

the first index of the tuple is the dependencies of the package named in the second index of the tuple

(absl-py depends on six for example)

What I would like to get is something which show the dependencies and the dependant packages, likes this:

sorted_packages = [('six', ['absl-py', 'bleach', 'protobuf']), 
('html5lib', ['bleach']), ('args', ['clint']), ...]

I was able to extract all the dependencies packages using this :

# get packages
list_packages = [a for (x, a) in list_packages_dep]

# get dependencies and remove duplicates
list_dependencies = []
for pack in list_packages_dep :
    pack_list = pack[0]
    if list_dependencies == []:
        list_dependencies = [x.lower() for x in pack_list]
    else:
        for po in pack_list:
            if po.lower() in list_dependencies:
                pass
            else:
                list_dependencies.append(po.lower())
print(list_dependencies)

But I have the feeling that it's too complicated here. Is there a way to do this in an easier way?

CodePudding user response:

You can use collections.defaultdict:

from collections import defaultdict
list_packages_dep = [(['six'], 'absl-py'), (['html5lib', 'six'], 'bleach'), (['args'], 'clint'),
                     (['discord.py'], 'discord'), (['aiohttp'], 'discord.py'),
                     (['click', 'itsdangerous', 'Jinja2', 'Werkzeug'], 'Flask'),
                     (['importlib-metadata'], 'jsonpickle'), (['importlib-metadata'], 'Markdown'),
                     (['six'], 'protobuf'), (['comtypes', 'pypiwin32', 'pywin32'], 'pyttsx3'),
                     (['certifi', 'chardet', 'idna', 'urllib3'], 'requests')]

d = defaultdict(list)
for lst_dep, pkg in list_packages_dep:
    for dep in lst_dep:
        d[dep].append(pkg)

print(list(d.items()))
[('six', ['absl-py', 'bleach', 'protobuf']),
 ('html5lib', ['bleach']),
 ('args', ['clint']),
 ('discord.py', ['discord']),
 ('aiohttp', ['discord.py']),
 ('click', ['Flask']),
 ('itsdangerous', ['Flask']),
 ('Jinja2', ['Flask']),
 ('Werkzeug', ['Flask']),
 ('importlib-metadata', ['jsonpickle', 'Markdown']),
 ('comtypes', ['pyttsx3']),
 ('pypiwin32', ['pyttsx3']),
 ('pywin32', ['pyttsx3']),
 ('certifi', ['requests']),
 ('chardet', ['requests']),
 ('idna', ['requests']),
 ('urllib3', ['requests'])]
  • Related