Bryce Draper -3 years ago 63
Python Question

# Code works well, but doesn't seem very Pythonic - How can I improve this dictionary creation and the creation of combinations from that dictionary?

I've got two dictionaries which I turn in to a dictionary of lists using the code below. It works, but it seems like non-Pythonic way to do it. Basically, it's ugly and will need to be updated if either of my other dictionaries gets updated.

``````KeyWeight = {x: MCNWeight[AttributeName[x]] for x in AttributeName.keys()}

list1 = []
list2 = []
list3 = []
list4 = []
list5 = []
list6 = []
list7 = []
list8 = []
list9 = []

for x, y in KeyWeight.iteritems():
if y == 1:
list1.append(x)
elif y == 2:
list2.append(x)
elif y == 3:
list3.append(x)
elif y == 4:
list4.append(x)
elif y == 5:
list5.append(x)
elif y == 6:
list6.append(x)
elif y == 7:
list7.append(x)
elif y == 8:
list8.append(x)
elif y == 9:
list9.append(x)

KeyWeight = {1: list1, 2: list2, 3: list3, 4: list4, 5: list5, 6: list6, 7: list7, 8: list8, 9: list9}
``````

After that, I have a pretty gross nested for loop that creates all possible combinations of that dictionary (shown below). It gives the results I'm looking for and runs quickly, but I have the nagging feeling that there's a better way to do it.

``````MasterMCN = []
MCNs = None

for each1 in KeyWeight[1]:
MCNs = each1
for each2 in KeyWeight[2]:
MCNs2 = MCNs + '-' + each2
for each3 in KeyWeight[3]:
MCNs3 = MCNs2 + '-' + each3
for each4 in KeyWeight[4]:
MCNs4 = MCNs3 + '-' + each4
for each5 in KeyWeight[5]:
MCNs5 = MCNs4 + '-' + each5
for each6 in KeyWeight[6]:
MCNs6 = MCNs5 + '-' + each6
for each7 in KeyWeight[7]:
MCNs7 = MCNs6 + '-' + each7
for each8 in KeyWeight[8]:
MCNs8 = MCNs7 + '-' + each8
for each9 in KeyWeight[9]:
MCNs9 = MCNs8 + '-' + each9
MasterMCN.append(MCNs9)
``````

You don't need to preallocate those lists, use a `defaultdict` with `list` as values:

``````from collections import defaultdict

d = defaultdict(list)
for x, y in KeyWeight.iteritems():
d[y].append(x)
KeyWeight = d
``````

To create combinations from the list values you can simply use `itertools.combinations`. You can use this related answer that uses `itertools.product` and preserves key-value ordering as a guide.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download