0

I have 2 dictionaries that (simplified) look like this:

dict1 = {'X(0,0)': 1, 'X(0,1)': 3, 'X(1,0)':4, 'X(1,1)':2}
dict2 = {'X(0)': 'area1', 'X(1)': 'area2'}

I want to create a third dictionary with the keys of the first one and the values of the second one, if the dict2 key 'X(i)' is part of the dict1 key 'X(i,j)'. So the end result should be like this:

dict3 = {'X(0,0)': 'area1', 'X(0,1)': 'area1', 'X(1,0)':'area2', 'X(1,1)':'area2'}

I have tried following what was suggested here but it is not exactly what I want and cannot make it work.

gdaf
  • 33
  • 6
  • I don't understand that logic... I mean `X(1,0)` contains both `0` and `1`, why did you associate it with `area2` instead of `area1`? Also: why use a string? If you simply used tuples as strings it would be much easier... i.e. instead of `"X(0)"` and `"X(0,0)"` use `0` and `(0,0)` afterwards you can simply do `key1 in key2` instead of having to parse both... – Giacomo Alzetta Sep 19 '18 at 14:33
  • @GiacomoAlzetta Note the 'X(i)' and 'X(i,j)'. So we only need to look at the 1st number in the (i,j) pair. – PM 2Ring Sep 19 '18 at 14:34
  • Not very general, but I think this works for your situation: `{k: dict2[k[:3]+")"] for k, v in dict1.items()}` – pault Sep 19 '18 at 14:35
  • Will the numbers in those keys only ever be single digits? – PM 2Ring Sep 19 '18 at 14:35
  • @PM2Ring Yes indeed I only care if the first number in the (i,j) pair is common. They are the result of an optimization, so I prefer to keep them like that so it makes it easier to keep track of what is going on. The numbers in the keys are not single digits, but I don't want them in the final dictionary anyway. – gdaf Sep 19 '18 at 14:40
  • @PM2Ring in my case the dict1 has keys like 'X(i,j,k)' and dict2 like the ones shown above. But I only want to link the dict1 keys with the dict2 values basec on the first digit i that is why I didn't show the compete form. – gdaf Sep 19 '18 at 14:51
  • Ah, ok. That's fair enough. – PM 2Ring Sep 19 '18 at 14:53

3 Answers3

2

You can do something like this: But the approach is more specific to your problem.

print {key:dict2.get(key.split(',')[0]+')')for key in dict1}
# {'X(0,0)': 'area1', 'X(0,1)': 'area1', 'X(1,0)': 'area2', 'X(1,1)': 'area2'}

Conversion of X(0,0) to X(0) do like this,

In [29]: 'X(0,0)'.split(',')
Out[29]: ['X(0', '0)']

In [30]: 'X(0,0)'.split(',')[0]+')'
Out[30]: 'X(0)'
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
0

i suggest you create a temporary dictionary first (for the key look-up) and then make the final one:

tmp_dict = {key[:3]: value for key, value in dict2.items()}
# {'X(0': 'area1', 'X(1': 'area2'}
dict3 = {key: tmp_dict[key[:3]] for key, value in dict1.items()}
# {'X(0,0)': 'area1', 'X(0,1)': 'area1', 'X(1,0)': 'area2', 'X(1,1)': 'area2'}

this will work for single-digit coordinates only.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
0
dict3 ={}
for i in dict1:
    dict3[i]=dict2[i[:3]+")"]

For your case!

kur ag
  • 591
  • 8
  • 19