Python 3.x: Merge two dictionaries with same keys and values being array

后端 未结 4 1318
遥遥无期
遥遥无期 2021-01-20 12:13

Python version: 3.x

I have two dictionaries with same keys and the values are arrays. Most of the questions I saw here, for the required purpose, have only one value

4条回答
  •  终归单人心
    2021-01-20 12:18

    If you always have the same keys in both dicts, this should fit your needs:

    d3 = {key:np.hstack([d1[key],d2[key]]) for key in d1.keys()}
    

    Outputs:

    In [7]: d3
    Out[7]: 
    {(1, 'Autumn'): array([ 2.5,  4.5,  7.5,  9.5, 10.2, 13.3, 15.7, 18.8]),
     (1, 'Spring'): array([10.5, 11.7, 12.3, 15. , 15.6, 20. , 23. , 27. ])}
    

    But this relies on the assumption, that for every key there is a value and that every key appears in both dicts.

提交回复
热议问题