python字典中的值可以更改吗_替换Python字典中的值

1586010002-jmsa.png

I have 2 files, The first only has 2 columns

A 2

B 5

C 6

And the second has the letters as a first column.

A cat

B dog

C house

I want to replace the letters in the second file with the numbers that correspond to them in the first file so I would get.

2 cat

5 dog

6 house

I created a dict from the first and read the second. I tried a few things but none worked. I can't seem to replace the values.

import csv

with open('filea.txt','rU') as f:

reader = csv.reader(f, delimiter="\t")

for i in reader:

print i[0] #reads only first column

a_data = (i[0])

dictList = []

with open('file2.txt', 'r') as d:

for line in d:

elements = line.rstrip().split("\t")[0:]

dictList.append(dict(zip(elements[::1], elements[0::1])))

for key, value in dictList.items():

if value == "A":

dictList[key] = "cat"

解决方案

The issue appears to be on your last lines:

for key, value in dictList.items():

if value == "A":

dictList[key] = "cat"

This should be:

for key, value in dictList.items():

if key in a_data:

dictList[a_data[key]] = dictList[key]

del dictList[key]

d1 = {'A': 2, 'B': 5, 'C': 6}

d2 = {'A': 'cat', 'B': 'dog', 'C': 'house', 'D': 'car'}

for key, value in d2.items():

if key in d1:

d2[d1[key]] = d2[key]

del d2[key]

>>> d2

{2: 'cat', 5: 'dog', 6: 'house', 'D': 'car'}

Notice that this method allows for items in the second dictionary which don't have a key from the first dictionary.

Wrapped up in a conditional dictionary comprehension format:

>>> {d1[k] if k in d1 else k: d2[k] for k in d2}

{2: 'cat', 5: 'dog', 6: 'house', 'D': 'car'}

I believe this code will get you your desired result:

with open('filea.txt', 'rU') as f:

reader = csv.reader(f, delimiter="\t")

d1 = {}

for line in reader:

if line[1] != "":

d1[line[0]] = int(line[1])

with open('fileb.txt', 'rU') as f:

reader = csv.reader(f, delimiter="\t")

reader.next() # Skip header row.

d2 = {}

for line in reader:

d2[line[0]] = [float(i) for i in line[1:]]

d3 = {d1[k] if k in d1 else k: d2[k] for k in d2}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值