奇思妙想 · 2025年 1月 5日 0

不同编程语言的"字典”

10 次浏览
  • Python 用大括号和里面的键值对代表字典。

字典的增删查

  • Python 增加键值很简单,用变量新键值就代表增加。
    obj["new_property"] = "xxxx"
    删除键值用 del 语句:del obj["new_property"]
    查询有两种方式,一种是对象方括号访问 obj["new_property"],另一种是get方法:
    • obj.get("new_property", "If no this property, return the string")
      get方法可以解决第一种方法当属性不存在会直接报异常的问题。

字典遍历

  • Python 遍历字典很简单:
    for k, v in dict.items()
    单独遍历key: for k in dict.keys()
    单独遍历value: for v in dict.values()