列表附加替换先前附加的值

时间:2018-07-14 05:44:30

标签: python python-3.x list

我正在尝试将字典添加到列表中,问题是在将“ Chrome”和“ Firefox”值都添加到“列表”之后,我在两个条目的列表中仅看到firefox.exe。

我们非常感谢您的帮助。 请参见两个值都不相同的字典的打印语句。

MyItems = ["ChromeSetup.exe","firefox.exe"]
listofitems = [{"appId": "ChromeID", 'id': "0","name": 'ChromeSetup.exe','_id': 'ChromeUnique'},{"appId": "FireFoxID", 'id': "0","name": 'firefox.exe','_id': 'FireFoxUnique'} ]

__id = ""
appId = ""
result = []
Dict = {"installerParameters":"","managedApp":{"_id":__id, "appId":appId},"postInstallAction":0,"postInstallScript":{"_id":"0"},"preInstallScript":{"_id":"0"}}

for app in MyItems:
    for items in listofitems:
        if items['name'] == app:
            Dict["managedApp"]["_id"] = items['_id']
            Dict["managedApp"]["appId"] = items['appId']
            print("Dictionery",Dict)
            result.append(Dict)
            break

print("See the List", result)

结果:

Dictionery {'installerParameters': '', 'managedApp': {'_id': 'ChromeUnique', 'appId': 'ChromeID'}, 'postInstallAction': 0, 'postInstallScript': {'_id': '0'}, 'preInstallScript': {'_id': '0'}}
Dictionery {'installerParameters': '', 'managedApp': {'_id': 'FireFoxUnique', 'appId': 'FireFoxID'}, 'postInstallAction': 0, 'postInstallScript': {'_id': '0'}, 'preInstallScript': {'_id': '0'}}
See the List [{'installerParameters': '', 'managedApp': {'_id': 'FireFoxUnique', 'appId': 'FireFoxID'}, 'postInstallAction': 0, 'postInstallScript': {'_id': '0'}, 'preInstallScript': {'_id': '0'}}, {'installerParameters': '', 'managedApp': {'_id': 'FireFoxUnique', 'appId': 'FireFoxID'}, 'postInstallAction': 0, 'postInstallScript': {'_id': '0'}, 'preInstallScript': {'_id': '0'}}]

2 个答案:

答案 0 :(得分:5)

在for循环中定义字典。您当前正在写入同一个字典对象,列表包含对该对象的引用,该对象本身就是引用。结果,您不断修改同一对象。

MyItems = ["ChromeSetup.exe","firefox.exe"]
listofitems = [{"appId": "ChromeID", 'id': "0","name": 'ChromeSetup.exe','_id': 'ChromeUnique'},{"appId": "FireFoxID", 'id': "0","name": 'firefox.exe','_id': 'FireFoxUnique'} ]

__id = ""
appId = ""
result = []

for app in MyItems:
    for items in listofitems:
        if items['name'] == app:
            # I would try to find a better var name.
            Dict = {"installerParameters":"","managedApp":{"_id":__id, "appId":appId},"postInstallAction":0,"postInstallScript":{"_id":"0"},"preInstallScript":{"_id":"0"}}
            Dict["managedApp"]["_id"] = items['_id']
            Dict["managedApp"]["appId"] = items['appId']
            print("Dictionery",Dict)
            result.append(Dict)
            break

print("See the List", result)

答案 1 :(得分:3)

在循环的第二次运行中,您的字典对象Dict被覆盖。发生这种情况是因为您已在循环上方定义了Dict。最好在循环中定义Dict