Daniel - 1 year ago 59
Python Question

# Dictionary Combinations - Unequal Number of Keys & Values

I want to print all unique combinations of keys and values for this dictionary:

``````items = {'a':[10,100,1000],'b':[11,110],'c':[12,120]}
``````

Using the code,

``````for key, value in items.items():
print(key,value)
``````

``````b [11, 110]
c [12, 120]
a [10, 100, 1000]
``````

I would like to produce the following result given the dictionary:

``````b 11
b 110
c 12
c 120
a 10
a 100
a 1000
``````

Order of the key-value combinations is not important, but the result should preserve the relationship. As always, any recommended resources and/or search terms associated with this problem will be appreciated.

You were really close:

``````items = {'a':[10,100,1000],'b':[11,110],'c':[12,120]}

# iterate on key/items couple
for k,vl in items.items():
# iterate on all values of the list
for v in vl:
# print with a simple format
print("{} {}".format(k,v))
``````

output:

``````a 10
a 100
a 1000
c 12
c 120
b 11
b 110
``````

Note that you can use `for k,vl in sorted(items.items()):` to print the keys in the sorted order `(a,b,c)`, same goes for the inside list:

``````# iterate on key/items couple
for k,vl in sorted(items.items()):
# iterate on all values of the list
for v in sorted(vl):
# print with a simple format
print("{} {}".format(k,v))
``````

output:

``````a 10
a 100
a 1000
b 11
b 110
c 12
c 120
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download