[英]Replace Character in a Python Dictionary
I have python dictionary like this and sometimes I get an mdash or some other character (like "\—") that I need to replace with a simply hyphen.我有这样的 python 字典,有时我会得到一个 mdash 或其他一些字符(如“\—”),我需要用一个简单的连字符替换它们。 I've seen lots of ways to change keys and whole values of a dictionary but I just need to change this character.
我见过很多方法来改变字典的键和整个值,但我只需要改变这个字符。 Is there a way to do this such that they output is the dictionary with the character changed.
有没有办法做到这一点,以便他们输出的是字符已更改的字典。 Thanks
谢谢
dict={1:{'name':'Event','description':'Fireside Chat'}, 2: {'name':'Class','description':'Friendship — Day'} }
Iterate through the values with a loop:使用循环遍历值:
data = {1: {'name': 'Event', 'description': 'Fireside Chat'}, 2: {'name': 'Class', 'description': 'Friendship — Day'}}
for id, row in data.items():
for k, v in row.items():
data[id][k] = v.replace('\u20124', '-')
Or with a dict comprehension:或者使用字典理解:
data = {id: {k: v.replace('\u2014', '-') for k, v in row.items()} for id, row in data.items()}
Also: using keywords like 'dict' as variable names is bad practice.另外:使用像“dict”这样的关键字作为变量名是不好的做法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.