繁体   English   中英

如何遍历包含多个键的字典列表,并更改不同的键值?

[英]How to loop through a list of dictionaries that contain more than one key, and change different key values?

所以我以前在Python工作,最近我转而使用C#。 我一直在尝试用C#重新创建我的一个Python项目,但我还是陷入了涉及字典的问题。 在我的Python代码的一部分中,我创建了一些字典,每个字典有两个键,并将所有字典添加到列表中:

slot0 = {"itemID": 0, "amount": 0}
slot1 = {"itemID": 0, "amount": 0}
slot2 = {"itemID": 0, "amount": 0}

inv = [slot0, slot1, slot2]

然后,稍后,我循环浏览字典列表,并能够轻松更改itemID键和amount键的值:

 for slot in inv:
      if slot["item"] == 0:
           slot["item"] = 2
           slot["amount"] += 1
           break

但是,在C#中,它似乎并不那么容易。 我成功创建了词典并将它们添加到列表中:

Dictionary<string, int> slot0 = new Dictionary<string, int>() { { "itemID", 0 }, { "amount", 0 } };
Dictionary<string, int> slot1 = new Dictionary<string, int>() { { "itemID", 0 }, { "amount", 0 } };
Dictionary<string, int> slot2 = new Dictionary<string, int>() { { "itemID", 0 }, { "amount", 0 } };

List<Dictionary<string, int>> inv = new List<Dictionary<string, int>>();

private void Start()
{
    inv.Add(slot0);
    inv.Add(slot1);
    inv.Add(slot2);
}

但我不确定如何从Python代码复制for循环。 我知道foreach是一个东西,我可以将它与KeyValuePairs一起使用,但我很确定你不能用它来改变多个键的值。 如果有人可以提供帮助,那就太好了。 对不起,如果我的问题不太清楚; 我非常乐意澄清。

这可能不是最优雅的解决方案,但它与Python中的相匹配。 你会foreach在随后Python的名单-ing for很好。 之后,您将字典作为slot ,只需使用带有密钥的索引器来访问和更改其值。

// I use `var` because I believe it to be more "csharponic" ;).
foreach (var slot in inv)
{
    if (slot["itemID"] == 0) {
        slot["itemID"] = 2;
        slot["amount"] += 1;
        break;
    }
}

您应该查看字典文档以了解访问字典的可能问题。 在我的示例中,如果您使用的密钥不存在,则最终会出现KeyNotFoundException 为了使代码更健壮,请在@Sach建议的if添加密钥检查; 像这样:

if (slot.ContainsKey("itemID") && slot["itemID"] == 0) { ... }

为了完整TryGetValue ,您还可以使用TryGetValue

foreach (var slot in inv)
{
    var v = 0;
    if (slot.TryGetValue("itemID", out v) && v == 0)
    {
        slot["itemID"] = 2;
        slot["amount"] += 1;
        break;
     }
}

的好处,如@mjwills在评论中指出,将减少键查找次数(更多关于out这个 )。 Item[]ContainsKeyTryGetValue “接近O(1)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM