个人代码

原创
2019/12/04 00:06
阅读数 39
import json, time


# 读取字典
def openDists():
    with open("demo2.json", encoding="utf-8") as f:
        # print(f)
        data = json.load(f)
    return data


print(openDists())


# 把字典写成json文件
def wjson(data):
    with open("demo2.json", "w", encoding='utf-8') as f:
        json.dump(data, f, indent=2, sort_keys=True, ensure_ascii=False)


# 删除
def delDicts(picName, groupId):
    data = openDists()
    keys = list(data.keys())
    if str(groupId) in keys:
        slist = data[str(groupId)]
        newKey = str(time.time()).replace('.', '')
        if picName + '.jpg' in slist:
            slist.remove(picName + '.jpg')
            if picName + '.jpg' in slist:
                return 'value值已存在'
            else:
                data[str(newKey)] = [picName + '.jpg']
                wjson(data)
                return "删除成功"
        elif picName + '.png' in slist:
            slist.remove(picName + '.png')
            if picName + '.png' in slist:
                return 'value值已存在'
            data[str(newKey)] = [picName + '.png']
            wjson(data)
            return "删除成功"
        else:
            return 'value值不存在'
    else:
        return 'key值不存在'


# 添加
def addDists(picName, newGroupId):
    data = openDists()
    keys = list(data.keys())
    if str(newGroupId) not in keys:
        values = list(data.values())
        if picName + ".jpg" not in values:
            for i in values:
                if picName + ".jpg" in i:
                    return 'value已存在'
            else:
                value1 = list(data.values())
                print("---", value1)
                data[str(newGroupId)] = [picName + ".jpg"]
                wjson(data)
                return '添加成功'
        elif picName + ".png" not in values:
            for i in values:
                if picName + ".png" in i:
                    return 'value已存在'
            else:
                data[str(newGroupId)] = [picName + ".png"]
                wjson(data)
                return '添加成功'
        else:
            return 'value 值已存在'
    else:
        return 'key值已存在'


# 合并
def innerDist(oldgroupId, newGroupId):
    data = openDists()
    keys = list(data.keys())
    newKey = str(time.time()).replace('.', '')

    if (oldgroupId in keys and newGroupId not in keys) or (oldgroupId not in keys and newGroupId in keys):
        return None
    elif oldgroupId in keys and newGroupId in keys:
        oldList = data[oldgroupId]
        newList = data[newGroupId]
        # 合并列表
        inList = list(set(oldList + newList))
        # 删除字典之前的值
        del data[oldgroupId]
        del data[newGroupId]
        data[newKey] = inList
        wjson(data)
        return '合并成功'
    else:
        return "key值不存在"


print(innerDist("15754389403840292", "10"))
# print(delDicts('11', 4))
# print(addDists("220", 15))
展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部