Home > Mobile >  Destructure a `dict` of length one to assign its key and value to two variables in Python
Destructure a `dict` of length one to assign its key and value to two variables in Python

Time:07-01

I have a bunch of dictionaries with only one key-value pairs that are sometimes generated by one of the scripts I wrote, and I need to get rid of them.

To do this, I need to get the key and value of the dict. Minimal reproducible example to illustrate my intent:

d = {'a': 0}
assert len(d) == 1
k, v = list(d.items())[0]

Don't know if this is a duplicate, but I can't find an answer using Google.

Is there a simpler way to get k, v from d?


Edit

In case anyone's wondering, here is where the situation arises:

from pathlib import Path

def recur_dir(path, root=''):
    first = False
    if not root:
        assert Path(path).is_dir()
        root = path
        first = True
    report = {'folders': dict(), 'files': []}
    for element in Path(path).iterdir():
        if element.is_file():
            report['files'].append(element.name)
        elif element.is_dir():
           report['folders'].update(recur_dir(str(element).replace('\\', '/'), root))
    
    folders = report['folders']
    for name, folder in list(folders.items()):
        if not folder:
            folders.pop(name)
        if not folder.get('files', None):
            folders[name].pop('files', None)
            if len(folder['folders']) == 1:
                key, value = folder['folders'].popitem()
                folders[key] = value
                folders.pop(name)
        elif not folder['folders']:
            folders[name].pop('folders')
    
    if not report.get('files', None):
        report.pop('files', None)
    
    if first:
        return {path: report}
    else:
        return {path.replace(root, ''): report}

In short, I wrote a script that recursively lists the contents of any given directory, and some sub-directories are empty, other sub-directories may contain one sub-directory and nothing else.

I want to remove the empty sub-directories and join the names of sub-directories that contain only one sub-directory to remove unnecessary nesting levels.

This question is related to the second part, I have not yet figured out a way not to create unnecessary nesting levels in the first place...

CodePudding user response:

If you don't need the dict anymore (as your "get rid of them" suggests):

k, v = d.popitem()

If you do:

(k, v), = d.items()

Try it online!

  • Related