输出结果

  • 输出: dict_keys(['a', 'b', 'c'])
  1. dict1 = {'a': 1, 'b': 2, 'c': 3}
  2. keys = dict1.keys()
  3. print(keys)

判断dict_keys对象是否包含某个元素

  1. dict1 = {'a': 1, 'b': 2, 'c': 3}
  2. keys = dict1.keys()
  3. if "a" in keys:
  4. print("dict_keys中包含a")

遍历dict_keys

  1. dict1 = {'a': 1, 'b': 2, 'c': 3}
  2. keys = dict1.keys()
  3. for key in keys:
  4. print(key)

将dict_keys对象转化为列表

  1. dict1 = {'a': 1, 'b': 2, 'c': 3}
  2. keys = dict1.keys()
  3. key_list = list(keys)
  4. print(key_list)

求并、交、差集

  1. dict1 = {'a': 1, 'b': 2, 'c': 3}
  2. dict2 = {'d': 4, 'e': 5, 'a': 6}
  3. keys1 = dict1.keys()
  4. keys2 = dict2.keys()
  5. union = set(keys1) | set(keys2)
  6. intersection = set(keys1) & set(keys2)
  7. difference = set(keys1) - set(keys2)
  8. print("并集:", union)
  9. print("交集:", intersection)
  10. print("差集:", difference)