• python "二维" 字典(字典嵌套)


    基本用法

    今天读在movielens数据集的推荐系统代码读到"二维"字典的写法,这里学习记录一下

    def get_dict(records:list, type:str):#此处record为ratings表的前三项,userid movieid rating,通过上面一个函数分为训练和测试集
        # 先看看redis里面有没有,如果有直接返回type_dict
        if redis.exists(type+'_dict'):
            return pickle.loads(redis.get(type+'_dict'))
        #redis中没有的话,开始新建,记录依次为user_id movie_id rating
        user_movie = {} #新建一个字典
        for record in records:
            user_id = int(record[0])
            movie_id = int(record[1])
            rating = int(record[2])
            if user_id not in user_movie:
                user_movie[user_id]={}
            user_movie[user_id][movie_id] = rating #二维字典
    
    
    • user_movie是一个空字典
    • user_movie[user_id]这里新建了字典的第一维
    • user_movie[user_id][movie_id]新建了字典的第二维
    jupyter notebook中测试一下
    #在定义的时候初始化二维字典
    dict_2d = {'a' : {'a' : 1, 'b' : 3}, 'b' : {'a' : 6}}
    dict_2d['a']['a']
    1
    
    #一步一步的创建上面这个“二维”字典
    myDict = {}
    myDict['a'] = {}
    myDict['a']['a'] = 1
    myDict['a']['b'] = 3
    myDict['b'] = {}
    myDict['b']['a'] = 6
    #测试是不是每一个都读到了
    print(myDict['a']['a'])
    print(myDict['a']['b'])
    print(myDict['b']['a'])
    1
    3
    6
    

    将二维字典转换为二维数组

    dict_2d2 = {0: {0: 173, 1: 342, 2: 666, 3: 506, 4: 94},
     1: {0: 13, 1: 2171, 2: 1915, 3: 3075, 4: 630},
     2: {0: 0, 1: 265, 2: 5036, 3: 508, 4: 11},
     3: {0: 0, 1: 3229, 2: 2388, 3: 3649, 4: 193},
     4: {0: 3, 1: 151, 2: 591, 3: 1629, 4: 410}}
    

    res = np.array([list(item.values()) for item in dict_2d2.values()])

    res
    

    array([[ 173, 342, 666, 506, 94],
    [ 13, 2171, 1915, 3075, 630],
    [ 0, 265, 5036, 508, 11],
    [ 0, 3229, 2388, 3649, 193],
    [ 3, 151, 591, 1629, 410]])

    np.dot(res, res)
    

    array([[ 34657, 2626206, 5388006, 3477036, 375246],
    [ 32362, 15249467, 21525493, 19902168, 2241792],
    [ 3478, 3551848, 27088376, 5244774, 324900],
    [ 42556, 19454743, 27037378, 24771877, 2843925],
    [ 3712, 5807413, 7399801, 7378182, 584410]])

    参考:
    https://www.jb51.net/article/157025.htm
    https://gitee.com/earth_wyz/movieRS
    https://www.it1352.com/1594129.html

    日积月累,水滴石穿
  • 相关阅读:
    140704
    140703
    140702
    堆排序
    并查集
    140701
    这年暑假集训-140630
    vim for python
    hihocode 第九十二周 数论一·Miller-Rabin质数测试
    hdu 3157 Crazy Circuits 有源汇和下界的最小费用流
  • 原文地址:https://www.cnblogs.com/lonelyisland/p/14530925.html
Copyright © 2020-2023  润新知