简体   繁体   中英

Convert Python dictionary to list of tuples

I am working on a small task that includes:

my_filters = {'cat': 'apple,orange', 'day': '20200101,20200102'}

It should convert it into a list of tuples like this:

[

[[('cat', '=', 'apple'), ('day', '=', '20200101')]]
[[('cat', '=', 'apple'), ('day', '=', '20200102')]]
[[('cat', '=', 'orange'), ('day', '=', '20200101')]]
[[('cat', '=', 'orange'), ('day', '=', '20200102')]]

]

My code is working fine for 2 keys:

def my_recursive_fun(i):
    results = []

    if i == 5:
        return ""
    if i <= 2:
        if i % 2 == 0:
            results.append([(list(my_filters.keys())[0], '=', my_filters['cat'].split(",")[0]),
                            (list(my_filters.keys())[1], '=', my_filters['day'].split(",")[1])])

        else:
            print("[\n")
            results.append([(list(my_filters.keys())[0], '=', my_filters['cat'].split(",")[0]),
                            (list(my_filters.keys())[1], '=', my_filters['day'].split(",")[0])])

    elif i <= 4:
        if i % 2 == 0:
            results.append([(list(my_filters.keys())[0], '=', my_filters['cat'].split(",")[1]),
                            (list(my_filters.keys())[1], '=', my_filters['day'].split(",")[1])])

            print(results)
            print("\n]")
            return ""
        else:
            results.append([(list(my_filters.keys())[0], '=', my_filters['cat'].split(",")[1]),
                            (list(my_filters.keys())[1], '=', my_filters['day'].split(",")[0])])

    print(results)
    my_recursive_fun(i + 1)


if __name__ == '__main__':
    my_recursive_fun(1)

But when there are 4 keys in dictionary

my_filters = {'cat': 'apple,orange', 'day': '20200101,20200102', 'other': 'abc,cde', 'bis': '123,345'}

It should be like this:

[

[('cat','=','apple'),('day','=','20200101')],

[('cat','=','apple'),('day','=','20200102')],

[('cat','=','orange'),('day','=','20200101')],

[('cat','=','orange'),('day','=','20200102')],

[('other','=','abc'),('bis','=','123')],

[('other','=','abc'),('bis','=','345')],

[('other','=','cde'),('bis','=','123')],

[('other','=','cde'),('bis','=','345')]


]

So I am struggling when there are more keys in my dictionary. Thanks

Below is my solution to a variation on your problem that might give you some ideas of how to go about it. The differences in mine include: I use a real data structure for my_filters , ie lists instead of comma separated items in a string; this solution doesn't guarantee the order of results; this solution is destructive on my_filters :

my_filters = {
    'cat': ['apple', 'orange'],
    'day': ['20200101', '20200102'],
    'other': ['abc', 'cde'],
    'bis': [123, 345],
}

def recursive_filters(filters):
    my_results = []

    if filters:
        key, values = filters.popitem()

        results = recursive_filters(filters)

        for value in values:
            item = [key, '=', value]

            if results:
                for result in results:
                    my_results.append([*result, item])
            else:
                my_results.append([item])

    return my_results

print(*recursive_filters(my_filters), sep='\n')

OUTPUT

> python3 test.py
[['cat', '=', 'apple'], ['day', '=', '20200101'], ['other', '=', 'abc'], ['bis', '=', 123]]
[['cat', '=', 'orange'], ['day', '=', '20200101'], ['other', '=', 'abc'], ['bis', '=', 123]]
[['cat', '=', 'apple'], ['day', '=', '20200102'], ['other', '=', 'abc'], ['bis', '=', 123]]
[['cat', '=', 'orange'], ['day', '=', '20200102'], ['other', '=', 'abc'], ['bis', '=', 123]]
[['cat', '=', 'apple'], ['day', '=', '20200101'], ['other', '=', 'cde'], ['bis', '=', 123]]
[['cat', '=', 'orange'], ['day', '=', '20200101'], ['other', '=', 'cde'], ['bis', '=', 123]]
[['cat', '=', 'apple'], ['day', '=', '20200102'], ['other', '=', 'cde'], ['bis', '=', 123]]
[['cat', '=', 'orange'], ['day', '=', '20200102'], ['other', '=', 'cde'], ['bis', '=', 123]]
[['cat', '=', 'apple'], ['day', '=', '20200101'], ['other', '=', 'abc'], ['bis', '=', 345]]
[['cat', '=', 'orange'], ['day', '=', '20200101'], ['other', '=', 'abc'], ['bis', '=', 345]]
[['cat', '=', 'apple'], ['day', '=', '20200102'], ['other', '=', 'abc'], ['bis', '=', 345]]
[['cat', '=', 'orange'], ['day', '=', '20200102'], ['other', '=', 'abc'], ['bis', '=', 345]]
[['cat', '=', 'apple'], ['day', '=', '20200101'], ['other', '=', 'cde'], ['bis', '=', 345]]
[['cat', '=', 'orange'], ['day', '=', '20200101'], ['other', '=', 'cde'], ['bis', '=', 345]]
[['cat', '=', 'apple'], ['day', '=', '20200102'], ['other', '=', 'cde'], ['bis', '=', 345]]
[['cat', '=', 'orange'], ['day', '=', '20200102'], ['other', '=', 'cde'], ['bis', '=', 345]]
>

Hopefully this example will give your some ideas about how to approach a cleaner solution to your own problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM