Skip to content Skip to sidebar Skip to footer

Python Dictionary:removing A String From A Tuple( Which Is A Key .)

I've got a dictionary like dic ={('L', 'N', 'C'):6, ('N', 'L', 'C'):4, ('C', 'N', 'L'):3}) I want to remove the string 'C' from all keys. Is there any efficient way of doing so

Solution 1:

This can be done with a single dictionary comprehension:

>>> dic ={('L', 'N', 'C'):6, ('N', 'L', 'C'):4, ('C', 'N', 'L'):3}
>>> {tuple(l for l in k if l != 'C'):v for k,v in dic.items()}
{('L', 'N'): 6, ('N', 'L'): 4}

Note that the removal of 'C' makes ('N', 'L', 'C') and ('C', 'N', 'L') clash as they both become ('N', 'L'). It is not clear from the question how you wish to handle that.

Solution 2:

for k,v in dic.iteritems():
    if 'C' in k:
        dic[tuple(el for el in k if el!='C')] = dic.pop(k)

In this solution, only the keys that contain the element to eliminate are changed (new objects since tuples are immutable). The dictionary is modified in place and the values remain the same objects.

The following code shows that.

dico = {(1,2,8):'aa',  
        (25,8,45,9):'gerard',
        (268,54,0):'marine',
        (81,3,8,7):'emma',
        (7,9,6):'louis'}

print'  id(dico) : ',id(dico)
for k,v in dico.iteritems():
    printid(k),'%-25s' % repr(k),id(v),v

idk = [id(el) for el in dico]

for k,v in dico.iteritems():
    if8in k:
        dico[tuple(el for el in k if el!=8)] = dico.pop(k)

printprint'  id(dico) : ',id(dico)
for k,v in dico.iteritems():
    print'%d %-30s %d %s' %\
          (id(k), ('[new id] 'ifid(k) notin idk else'         ')+repr(k),id(v),v)

result

id(dico) :  18737456
18751976 (268, 54, 0)              18718464 marine
11258576 (1, 2, 8)                 18566968 aa
18539072 (25, 8, 45, 9)            18603776 gerard
18606768 (81, 3, 8, 7)             18718432 emma
18752056 (7, 9, 6)                 18718592 louis

  id(dico) :  18737456
18752216 [new id] (1, 2)                18566968 aa
18751976          (268, 54, 0)          18718464 marine
18752176 [new id] (81, 3, 7)            18718432 emma
18752056          (7, 9, 6)             18718592 louis
18752416 [new id] (25, 45, 9)           18603776 gerard

Post a Comment for "Python Dictionary:removing A String From A Tuple( Which Is A Key .)"