[英]Retrieve a key-value pair from a dict as another dict
I have a dictionary that looks like: 我有一本字典,看起来像:
{u'message': u'Approved', u'reference': u'A71E7A739E24', u'success': True}
I would like to retrieve the key-value pair for reference, ie { 'reference' : 'A71E7A739E24' }
. 我想检索键值对以供参考,即
{ 'reference' : 'A71E7A739E24' }
。 I'm trying to do this using iteritems
which does return k, v
pairs, and then I'm adding them to a new dictionary. 我正在尝试使用
iteritems
来执行此操作,该iteritems
会返回k, v
对,然后将它们添加到新字典中。 But then, the resulting value is unicode
rather than str
for some reason and I'm not sure if this is the most straightforward way to do it: 但是然后,由于某种原因,结果值是
unicode
而不是str
,我不确定这是否是最简单的方法:
ref = {}
for k, v in charge.iteritems():
if k == 'reference':
ref['reference'] = v
print ref
{'reference': u'A71E7A739E24'} {'参考':u'A71E7A739E24'}
Is there a built-in way to do this more easily? 有内置的方法可以更轻松地执行此操作吗? Or, at least, to avoid using
iteritems
and simply return: 或者至少,为了避免使用
iteritems
,只需返回:
{ 'reference' : 'A71E7A739E24' }
使用迭代项的麻烦在于将查找时间增加到O(n),其中n是字典大小,因为您不再使用哈希表
I dont understand the question: 我不明白这个问题:
is this what you are trying to do: 这是您要执行的操作:
ref={'reference',charge["reference"]}
If you only need to get one key-value pair, it's as simple as 如果您只需要获取一个键值对,则只需
ref = { key: d[key] }
If there may be multiple pairs that are selected by some condition, 如果某个条件可能选择了多对,
either use dict
from iterable constructor (the 2nd version is better if your condition depends on values, too): 要么使用可迭代构造函数中的
dict
(如果您的条件也取决于值,则第二个版本更好):
ref = dict(k,d[k] for k in charge if <condition>)
ref = dict(k,v for k,v in charge.iteritems() if <condition>)
or (since 2.7) a dict comprehension (which is syntactic sugar for the above): 或(自2.7起) dict理解 (以上所述为语法糖):
ref = {k,d[k] for k in charge if <condition>}
<same as above>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.