Using Python Docopt (for beautiful command-line interfaces) I recently had the problem of converting a list of tuples into a dictionary. In this post I’d like to document the solution…

"""
usage:
    mytool [options]

options:
    --foo-bar=PARAM1,PARAM2,... params to do stuff with
        [default: key1.value1,key1.value2,key2.value2]
"""

from docopt import docopt
from collections import defaultdict


def run():
    params = [tuple(param.strip().split('.')) for param in arguments["--foo-bar"].split(",")]
    params = convert_tuple_list_to_dictionary(ignored_resources)

def convert_tuple_list_to_dictionary(list_of_tuple):
    dictionary = defaultdict(list)
    for k, v in list_of_tuple:
        dictionary[k].append(v)

    return dictionary

if __name__ == "__main__":
    run()

This code is able to convert the parameter value string key1.value1,key1.value2,key2.value2 into the following dictionary:

{
	'key1': ['value1', 'value2'],
    'key2': ['value2']
}

If you know a leaner solution to solve this problem, let me know!

Cite this

Jan Brennenstuhl. “Python Docopt: Convert Tuple List to Dictionary.” Brennenstuhl on Security, 28 April 2015. https://www.janbrennenstuhl.eu/python-tuples-to-dict/

APA and BibTeX
APA

Brennenstuhl, J. (2015, April 28). Python Docopt: Convert Tuple List to Dictionary. Brennenstuhl on Security. https://www.janbrennenstuhl.eu/python-tuples-to-dict/

BibTeX
@online{brennenstuhl2015python,
  author = {Brennenstuhl, Jan},
  title = {Python Docopt: Convert Tuple List to Dictionary},
  date = {2015-04-28},
  organization = {Brennenstuhl on Security},
  url = {https://www.janbrennenstuhl.eu/python-tuples-to-dict/}
}

Markdown version ID jb-python-tuple-list-to-dict CC BY 4.0 Send a correction