简体   繁体   中英

How do I create permutations of of each keys from dictionary?

Say I have a dictionary of letters with assigned values:

  dictionary = {"l":"smias", "k":"swdw", 'm':'blala'}

how do i create permutations of keys without duplicates and return them as tuples like this?

  mytuple = ((l,k),(l,m),(k,m))

You can try this without using libraries.

def combinations(lst, length, idx, cur, res):
    # length: length of each item in combinations
    if length == 0:
        res.append(tuple(cur))
        return
    for i in range(idx, len(lst)):
        combinations(lst, length - 1, i + 1, cur + [lst[i]], res)

res = []
dictionary = {"l":"smias", "k":"swdw", 'm':'blala'}
combinations(list(dictionary.keys()), 2, 0, [], res)
mytuple = tuple(res)
# (('l', 'k'), ('l', 'm'), ('k', 'm'))

Your example is combinations, not permutations. You can get either with itertools :

from itertools import combinations

d = {"l":"smias", "k":"swdw", 'm':'blala'}

tuple(combinations(d, r=2))
# (('l', 'k'), ('l', 'm'), ('k', 'm'))

Or permutations:

from itertools import permutations

d = {"l":"smias", "k":"swdw", 'm':'blala'}

tuple(permutations(d, r=2))
# (('l', 'k'), ('l', 'm'), ('k', 'l'), ('k', 'm'), ('m', 'l'), ('m', 'k'))

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