18

我有 2 个字典:

dicts1 = {'field1':'', 'field2':1, 'field3':1.2}
dicts2 = {'field1':123, 'field2':123, 'field3':'123'}

我想将 in 中的每个值转换dict2为与 in 中相应值相同的类型,dict1最快的 pythonic 方式是什么?

4

3 回答 3

31

假设它们是兼容的类型:

for k, v in dicts1.iteritems():
    try:
        dicts2[k] =  type(v)(dicts2[k])
    except (TypeError, ValueError) as e:
        pass # types not compatible
    except KeyError as e:
        pass # No matching key in dict
于 2012-07-12T15:10:06.837 回答
3

这一个班轮会做到这一点 - 但它不检查类型错误:

dicts1 = {'field1':'', 'field2':1, 'field3':1.2}
dicts2 = {'field1':123, 'field2':123, 'field3':'123'}

print {k : type(dicts1[k])(dicts2[k]) for k in dicts2}

这也可以做到 - 并且对于某些人来说可能更具可读性:

print {k : type(dicts1[k])(v) for (k,v) in dicts2.iteritems()}
于 2012-07-12T15:12:57.637 回答
0

Pydantic 是动态类型转换的答案。

如果值的类型dicts1将成为 中值类型的引用,dict2则将 dicts1 转换为扩展为的类通常是个好主意pydantic.BaseModel

from pydantic import BaseModel

class dicts1(BaseModel):
    field1: str
    field2: int
    field3: float

dicts2 = dict(dicts1(**{'field1':123, 'field2':123, 'field3':'123'}))
print(dicts2)

输出:{'field1':'123','field2':123,'field3':123.0}

于 2021-09-03T11:09:44.253 回答