Python 字典值指针是否存储其键?

在 Python 中,字典是一种常用的数据结构,它允许通过键值对来存储数据。当我们需要访问字典中的某个值时,可以通过键来获取。但是,如果我们只有一个值,而没有对应的键,那么是否有办法获取键?
在这里插入图片描述

2、解决方案

Python 自身并没有提供内置的方式来实现这个功能。这是因为字典的键必须是不可变对象,例如字符串、数字和元组,而值可以是任何类型的对象。如果 Python 存储键的指针,那么当值更改时,键也可能会发生更改,这会导致字典的键不再唯一,从而破坏字典的结构。

因此,如果我们想获取键,需要自己维护一个键值映射,或者在值中存储键。

下面是一个简单的例子,演示如何维护一个键值映射:

def get_key_from_value(value, key_value_map):
  for key, value_in_map in key_value_map.items():
    if value_in_map == value:
      return key
  return None

d = {'one': objectA(), 'two': objectB(), 'three': objectC()}
object_a = d['one']

key = get_key_from_value(object_a, d)
print(key)  # one

这个例子中,我们创建了一个字典 d,其中包含三个键值对。然后,我们从字典中获取值 object_a,并使用 get_key_from_value 函数来获取 object_a 对应的键。

get_key_from_value 函数遍历字典 d,并比较每个键值对中的值与 object_a。如果找到匹配的值,则返回相应的键。如果没有找到匹配的值,则返回 None。


# dict_example.py

# Simple Python program explaining the difference between
# mutable and immutable objects.

# Python program to illustrate the
# dictionary key-value pair

dict1 = {1: "geeks", 2: "for", 3: "geeks"}

# accesing values using key
print(dict1[3])

# updating value using key
dict1[3] = "welcomes"

# accesing values using key
print(dict1[3])

# Python program to illustrate the
# dictionary key-value pair


# Key should be immutable
class DictKey:

	def __init__(self, value):
		self.value = value

	def __hash__(self):
		return hash(self.value)

	def __eq__(self, other):
		return (self.value == other.value)

# Key should be mutable
class MutableDictKey:
	def __init__(self, value):
		self.value = value

# create object i.e. key for dictionary
mutable_key = MutableDictKey("MutableKey")
normal_key = DictKey("NormalKey")

# creating dictionary
dict1 = {mutable_key : 1, normal_key : 2, }

# printing values of hash
print("Hash Values : ")
print(hash(mutable_key))
print(hash(normal_key))

# updating the value of class object
mutable_key.value = "New Key"

# dictionary cannot be updated as key is not immutable
try:
	dict1[mutable_key] = 10
except TypeError as e:
	print(e)


# Python code to demonstrate the solution
# of storing key's inside the value

# Initializing dictionary
test_dict = {
	'Gfg' : {
		'is' : 'best'
	},
	'for' : {
		'geeks' : 'CS'
	}
}

# Printing original dictionary
print("The original dictionary is : ", test_dict)

# Key's inside the values
temp = {}
res = {}

# Using loop to iterate and get keys
for key, sub_dict in test_dict.items():
	for sub_key, sub_value in sub_dict.items():
		
		# Storing key inside value
		sub_dict[sub_key] = sub_dict[sub_key] + ' ' + key

		# Updating temp dict
		temp[key] = temp.get(key, []) + [sub_key]

# Adding value to result dict
for key, lst in temp.items():
	
	# Checking if more than 1 keys to cater nesting
	if len(lst) > 1:
		
		# Adding list
		res[key] = lst
	
	# Adding item
	else:
		res[key] = lst[0]

# Printing result
print("The dictionary after inclusion of key : ", res)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值