python 以值查键
时间: 2023-11-22 21:50:26 浏览: 74
以下是三种Python以值查键的方法:
1. 使用zip函数和filter函数
```python
tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
target = list(filter(lambda t: t[0][1] == 7, zip(tinydict.items())))
if target:
ret = dict(target[0])
print('方式1', ret) # 输出:{'Age': 7}
```
2. 使用字典的items函数和filter函数
```python
tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
target = list(filter(lambda x: x[1] == 7, tinydict.items()))
if target:
ret = dict(target)
print('方式2', ret) # 输出:{'Age': 7}
```
3. 使用for循环
```python
tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
target = {k: v for k, v in tinydict.items() if v == 7}
print('方式3', target) # 输出:{'Age': 7}
```
相关问题
python 字典以值查键
可以通过遍历字典的键值对,找到对应值所对应的键。以下是一个例子:
```python
# 定义一个字典
dicxx = {'a':'001', 'b':'002', 'c':'001'}
# 定义一个函数,接收一个字典和一个值作为参数
def get_keys(d, value):
# 定义一个空列表,用于存储所有符合条件的键
keys = []
# 遍历字典的键值对
for k, v in d.items():
# 如果值等于目标值,则将对应的键添加到列表中
if v == value:
keys.append(k)
# 返回列表
return keys
# 调用函数,查找值为'001'的键
print(get_keys(dicxx, '001')) # 输出:['a', 'c']
```
python字典以键查值
在Python中,可以使用字典来以键查找值。下面是一个示例代码:
```python
d = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
# 通过键查找值
value = d['one']
print(value) # 输出:1
```
在上面的代码中,我们创建了一个字典`d`,其中键是字符串,值是整数。然后,我们使用键`'one'`来查找对应的值,并将其赋给变量`value`。最后,我们打印出`value`的值,即1。
需要注意的是,如果字典中不存在指定的键,会抛出`KeyError`异常。为了避免这种情况,可以使用`get()`方法来查找值,如果键不存在,则返回指定的默认值。下面是一个示例代码:
```python
d = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
# 通过键查找值,如果键不存在,则返回默认值
value = d.get('five', 0)
print(value) # 输出:0
```
在上面的代码中,我们使用`get()`方法来查找键`'five'`对应的值,由于键不存在,所以返回了指定的默认值0。
阅读全文
相关推荐
















