简体   繁体   中英

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' } . I'm trying to do this using iteritems which does return k, v pairs, and then I'm adding them to a new dictionary. 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:

ref = {}
for k, v in charge.iteritems():
    if k == 'reference':
        ref['reference'] = v
        print ref

{'reference': u'A71E7A739E24'}

Is there a built-in way to do this more easily? Or, at least, to avoid using iteritems and simply return:

{ '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):

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):

ref = {k,d[k] for k in charge if <condition>}
<same as above>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM