user3188922
user3188922

Reputation: 349

Replace dict key by value of other dict

Today I need to replace the key of dict one by value of dict two. Dict one has multiple keys and I only want to replace the keys which match dict 2. In the end I want to get the dict one back with the old keys (the ones which did not match) and the new keys (which have been changed when they matched)

I wrote the following script but I get no output so I am not sure if I am doing it right, can someone explain to me?

Thanks a lot

ERCC = {}
my_file = open('a.txt')
for line in my_file:
    config,name = line.strip().split()
    ERCC[contig] = name

RSEM = {}
names_file = open('b.txt')
for line in names_file:
    genes, count = line.strip().split()
    RSEM[gene] = count

def convert(RSEM,ERCC):
    for key, value in RSEM.items():
        for keys, values in ERCC.items():
            if keys == key:
                RSEM[key] = values
    return RSEM
    print RSEM

convert(RSEM, ERCC)

Upvotes: 0

Views: 786

Answers (3)

nish
nish

Reputation: 7280

Your code seems to be fine. But you have used return statement before print statement. The execution of convert function stops at return *** and the print statement is not executed at all. That is the reason why you are not getting any output.

Upvotes: 0

Benjamin
Benjamin

Reputation: 2286

     >>> dic={}
    >>> for k,v in myboi.items():
r=input("Enter item to Update write in ""=")
if r:
    dic[r]=v
else:
    dic[k]=v
    Enter item to Update write in ="Mahesh"
    Enter item to Update write in ="Saka"
    >>> 
    >>> dic
    {'Mahesh': 'Mahesh', 'Saka': 'Mahesh'}
   You want compulsary input key in this program you want update one or more time you empty dic={}
   result={'Mahesh': 'Mahesh', 'Saka': 'Mahesh'}


    >>> fi.close()
   >>> fi=open("m.txt","r")
   >>> fi.readlines()
    ['Maheshname']
   >>> fi=open("m.txt","w+")
   >>> for k,v in myboi.items():
fi.write("'"+k+"'"+":"+"'"+v+"'")


    >>> fi.close() 
    >>> fi=open("m.txt","r")
    >>> fi.readlines()
   ["'Mahesh':'Mahesh''name':'Mahesh'"]

Upvotes: 1

Grisha S
Grisha S

Reputation: 838

Here's a two-liner for the convert function:

RSEM = {key: ERCC.get(key, RSEM[key]) for key in RSEM}
print RSEM

To dump a dict to a file just do:

with open("your_file_name", "w") as dumpfile:
    dumpfile.write(str(RSEM))

Upvotes: 0

Related Questions