我有一个像这样的python字典:
# cellset is the dictionary
for x in cellset:
x.replace('Live','Live1')
取代' Live'的最佳方式是什么?字符串' Live2'对于字典中的所有键?
我已经尝试了以下但是它抛出了一个错误:
pq = [] # list of entries arranged in a heap
entry_finder = {} # mapping of tasks to entries
REMOVED = '<removed-task>' # placeholder for a removed task
counter = itertools.count() # unique sequence count
def add_task(task, priority=0):
'Add a new task or update the priority of an existing task'
if task in entry_finder:
remove_task(task)
count = next(counter)
entry = [priority, count, task]
entry_finder[task] = entry
heappush(pq, entry)
def remove_task(task):
'Mark an existing task as REMOVED. Raise KeyError if not found.'
entry = entry_finder.pop(task)
entry[-1] = REMOVED
def pop_task():
'Remove and return the lowest priority task. Raise KeyError if empty.'
while pq:
priority, count, task = heappop(pq)
if task is not REMOVED:
del entry_finder[task]
return task
raise KeyError('pop from an empty priority queue'
AttributeError:&#39; tuple&#39;对象没有属性&#39;替换&#39;
答案 0 :(得分:1)
d = {
('Live', '2017-Jan', '103400000', 'Amount'): 30,
('Live', '2017-Feb', '103400000', 'Amount'): 31,
('Live', '2017-Mar', '103400000', 'Amount'): 32,
('Live', '2017-Jan', '103401000', 'Amount'): 34
}
new_d = {}
for k, v in d.items():
new_key = tuple('Live1' if el == 'Live' else el for el in k)
new_d[new_key] = v
print(new_d)
# Output:
# {('Live1', '2017-Jan', '103400000', 'Amount'): 30, ('Live1', '2017-Feb', '103400000', 'Amount'): 31, ('Live1', '2017-Mar', '103400000', 'Amount'): 32, ('Live1', '2017-Jan', '103401000', 'Amount'): 34}
答案 1 :(得分:1)
其他人向您展示了如何使用'Live1'替换'Live'来创建新词典。如果您希望在原始字典中进行这些替换,可能的解决方案将类似于此
for (head, *rest), v in tuple(d.items()):
if head == "Live":
d[("Live1", *rest)] = v
del d[(head, *rest)]