最新消息:20210917 已从crifan.com换到crifan.org

【已解决】Python中向dict字典中的某个指定的key的后面插入值

Python crifan 458浏览 0评论
折腾:
【未解决】更新ViVoGame的autoSearchGame脚本生成魔域游戏信息列表
期间,希望对于一个已有的dict字典:
{
    "id": 62990,
    "pkgName": "com.m37.dldl.vivo",
。。。
    "apkurl": "https://dlweb.gamecenter.vivo.com.cn/clientRequest/gameDownload?id=62990&pkgName=com.m37.dldl.vivo&channel=h5",
    "comment": 4.0,
...
想要插入:
"realApkUrl": "https://gameapktxdl.vivo.com.cn/appstore/developer/soft/20200831/202008311206380xgm8.apk"
到dict中apkurl的后面
而不是:默认只会插入到dict的最末尾:
注:此处用最新的3.7+的Python,知道Python的dict是默认可以保留key的顺序的
Add a new item to a dictionary in Python – Stack Overflow
python – How can I add new keys to a dictionary? – Stack Overflow
python dict insert key after
Python add to Dictionary – JournalDev
How to insert dict key after specific key – Users – Discussions on Python.org
https://discuss.python.org/t/how-to-insert-dict-key-after-specific-key/4198
记得新python的dict的key是有index的?
找到index后,insert或许就可以了?
python dict key index
How to get the index with the key in Python dictionary? – Stack Overflow
OrderedDict 有:
x.keys().index("d")
去试试
Python: get key of index in dictionary – Stack Overflow
i={'foo':'bar', 'baz':'huh?'}
keys=i.keys()  #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")]  #'foo'
这个办法不错
python – How to index into a dictionary? – Stack Overflow
python dict insert
Python : How to add / append key value pairs in dictionary – thispointer.com
https://thispointer.com/python-how-to-add-append-key-value-pairs-in-dictionary-using-dict-update/
Python Add to Dictionary: A Guide
dict没有:add(), append(), or insert()
算了,自己实现
def insertKeyValueAfterDictKey(curDict, afterKey, newKey, newValue):
    """Insert new key and new value after specific key


    Args:
        afterKey (str): name of after the key
        newKey (str): new key to insert
        newValue (Any?): new value to insert
    Returns:
    Raises:
    """
    keyList = curDict.keys()
    valuesList = curDict.values()
    afterKeyIndex = keyList.index(afterKey)
    keyList.insert(afterKeyIndex, newKey)
    valuesList.insert(afterKeyIndex, newValue)
    updatedDict = {}
    for keyIdx, eachKey in enumerate(keyList):
        eachValue = valuesList[keyIdx]
        updatedDict[eachKey] = eachValue
    return updatedDict
去调试看看
发现insert是插入到上面了。此处选择去插入到下面
    keyList = list(curDict.keys())
    keyMaxNum = len(keyList)
    keyMaxIdx = keyMaxNum - 1
    # valuesList = curDict.values()
    valuesList = list(curDict.values())
    afterKeyIndex = keyList.index(afterKey) # 6
    if afterKeyIndex < keyMaxIdx:
        toInsertIndex = afterKeyIndex + 1
        keyList.insert(afterKeyIndex, newKey)
        valuesList.insert(afterKeyIndex, newValue)
    else:
        keyList.append(newKey)
        valuesList.append(newValue)
继续调试
调用代码:
detailGameInfo = insertKeyValueAfterDictKey(detailGameInfo, "apkurl", "realApkUrl", detailRealApkUrl)
可以在apkurl后面插入realApkUrl的key了:
也插入了对应的realApkUrl的值:
最后更新后的dict就是我们要的结果了:
【总结】
最后完整代码:
def insertKeyValueAfterDictKey(curDict, afterKey, newKey, newValue):
    """Insert new key and new value after specific key


    Args:
        afterKey (str): name of after the key in dict
        newKey (str): new key to insert
        newValue (Any?): new value to insert
    Returns:
    Raises:
    """
    # keyList = curDict.keys()
    keyList = list(curDict.keys())
    keyMaxNum = len(keyList)
    keyMaxIdx = keyMaxNum - 1
    # valuesList = curDict.values()
    valuesList = list(curDict.values())
    afterKeyIndex = keyList.index(afterKey) # 6
    if afterKeyIndex < keyMaxIdx:
        toInsertIndex = afterKeyIndex + 1
        keyList.insert(toInsertIndex, newKey)
        valuesList.insert(toInsertIndex, newValue)
    else:
        keyList.append(newKey)
        valuesList.append(newValue)
    updatedDict = {}
    for keyIdx, eachKey in enumerate(keyList):
        eachValue = valuesList[keyIdx]
        updatedDict[eachKey] = eachValue
    return updatedDict
调用:
detailGameInfo = insertKeyValueAfterDictKey(detailGameInfo, "apkurl", "realApkUrl", detailRealApkUrl)
即可。

转载请注明:在路上 » 【已解决】Python中向dict字典中的某个指定的key的后面插入值

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
92 queries in 0.186 seconds, using 23.34MB memory