用值替换字典键

时间:2015-10-14 02:37:45

标签: python dictionary

我已经从文本文件中创建了一个字典,并希望用它来替换出现在单独文件中的键及其值。

例如,我的字典看起来像......

names = {1:"Bob", 2:"John", 3:"Tom"}

另一个文件看起来像......

1 black cat  
2 gray elephant  
3 brown dog  

我希望它最终成为......

Bob black cat  
John gray elephant  
Tom brown dog  

到目前为止,我只编写了制作字典的代码

names = {}  
for line in open("text.txt", 'r'):  
    item = line.split()  
    key, value = item[0], item[2]  
    names[key] = value  

我想打开第二个文件并使用名称字典将其中出现的键替换为其值。我已经看到你可以使用replace(key, dict[key]),但我不确定如何。

6 个答案:

答案 0 :(得分:3)

如果您正在使用词典,我会将它们加载到两个单独的词典中然后合并它们。

如果您已将名称加载到names,将动物加载到animals,则可以将它们合并为:

merged = {}
for key, name in names.iteritems():
    merged[name] = animals[key]

答案 1 :(得分:0)

您可以遍历字典值并使用replace

for key in names:
    text = text.replace(key, names[key])

(保存text您文件的内容。)

答案 2 :(得分:0)

这是一种方式:

def last_delivery; object.delivery_addresses.last; end

答案 3 :(得分:0)

mydict = {1:"Bob", 2:"John", 3:"Tom"} # this is already a dicionary so do nothing
mydict2 = {}
myfile = """1 black cat
2 gray elephant
3 brown dog
"""


# you should use with open(file, 'r') as data:  --> fyi 

# convert the file to a dictionary format
for line in myfile.split('\n'):
  chunks = line.split(' ')
  if chunks != ['']: # i needed this because of the some white space in my example
    key, value = chunks[0], chunks[1] + ' ' + chunks[2]
    mydict2[key] = value

# remember dictionaries are not sorted, so there is no guarantee things will
# match as you expect, however there is plenty of documentation
# that you can follow to sort the dictionary prior to what i'm doing below
# i'm assuming that there are always the same number of items in both dictionaries
new_dict = {}
new_values = mydict2.values() # create a list of all the values
# iterate over the dictionary item
index = 0
for k, v in mydict.items():
 new_dict[v] = new_values[index] # append the value of the first dictionary with the value from the list
 index += 1

print new_dict 

答案 4 :(得分:0)

您可以直接写入新文件,并重定向到names 你还需要对行的其余部分进行切片(item[2]只得到第3个元素)并将它们连接在一起:

names = {1:"Bob", 2:"John", 3:"Tom"}
with open("text.txt", 'r') as r, open('out.txt', 'w') as w:
    for line in fp:
        item = line.split()  
        key, value = item[0], item[1:]    # Python 2
        # key, *value = item              # Python 3
        w.write("{} {}".format(names[int(key)], ' '.join(value)))

$ cat out.txt
Bob black cat
John gray elephant
Tom brown dog

答案 5 :(得分:0)

尝试以下代码:

new_dict = {value:key for (key,value) in old_dict.items()}