0

I have a dictionary A containing day as a key, and list of strings as a values example:

A = {"day1": ['A', 'B', 'C']}.

How can I create a List B containing the unique relationships that will be established Lists?

B = [['A','B'], ['A','C'], ['B','C']]
jpp
  • 159,742
  • 34
  • 281
  • 339

2 Answers2

3
>>> import itertools
>>> A = {"day1": ['A', 'B', 'C']}
>>> seq = A["day1"]
>>> list(itertools.combinations(seq, r=2))
[('A', 'B'), ('A', 'C'), ('B', 'C')]
Kevin
  • 74,910
  • 12
  • 133
  • 166
0
A = {"day1": ['A', 'B', 'C']}
B = [['A','B'], ['A','C'], ['B','C']]

vals = A['day1']
connections = []
for val in vals:
    connections_to_val = [(val, x) for x in vals 
        if (val != x and (x, val) not in connections)]
    connections.extend(connections_to_val)
Matt_G
  • 50
  • 1
  • 6
  • Thank you it works, but I didn't understand how connections_to_val works can you simplify it to separated for and if statements – ibrahim hammoud Jun 07 '18 at 12:43
  • connections_to_val is a list comprehension that basically loops through the values in vals = ('A', 'B', 'C') using the variable x and for every value it appends the tuple (val, x). So we append the tuple (val, x) if the conditions (val!=x and x,val not in connections) is true. That means that we don not want to append tuples where val and x are equal (i.e. ('A', 'A') and tuples that are already in the list but in opposite order (i.e. if ('A', 'B') is in there, do not append ('B', 'A'). – Matt_G Jun 08 '18 at 13:40