0

I have two lists x = ['high', 'low', 'high'] and y = ['volume', 'value', 'value']

And i would like to have a dict like {'volume': ['high'], 'value': ['low', 'high']}

How to do it simply? Thanks

Julio
  • 67
  • 6
  • 1
    Have you managed to do it complicated…? – deceze Aug 31 '22 at 10:02
  • [Iterate over the key-value pairs in parallel](https://stackoverflow.com/questions/1663807/how-do-i-iterate-through-two-lists-in-parallel) and [add each into a new dictionary, merging the values as you go](https://stackoverflow.com/questions/5946236/how-to-merge-dicts-collecting-values-from-matching-keys). There is unfortunately no real shortcut. – Karl Knechtel Aug 31 '22 at 10:03

1 Answers1

2

Simply, you can zip two list, if the key is not exist, you can create and array and append the new value. Otherwise you can directly append to array.

my_dict={}
x = ['high', 'low', 'high'] 
y = ['volume', 'value', 'value']
for x_value, y_value in zip(x, y):
    if y_value in my_dict:
        my_dict[y_value].append(x_value)
    else:
        my_dict[y_value]=[(x_value)]
print(my_dict)
Ogün Birinci
  • 598
  • 3
  • 11