遍历嵌套的字典
问题描述:
内部列表可以说我有这样的词典:遍历嵌套的字典
myDict = {
1: {
"a": "something",
"b": [0, 1, 2],
"c": ["a", "b", "c"]
},
2: {
"a": "somethingElse",
"b": [3, 4, 5],
"c": ["d", "e", "f"]
},
3: {
"a": "another",
"b": [6, 7, 8],
"c": ["g", "h", "i"]
}
}
这是我的代码:
for id, obj in myDict.items():
for key, val in obj.items():
if key is "b":
for item in val:
# apply some function to item
有没有更好的方式来遍历一个列表内嵌字典?或者有没有pythonic的方式来做到这一点?
答
如果你的字典总是两层深,我没有看到你的方法有什么问题。在你的实现中,我将使用key == "b"
而不是key is "b"
。使用is
将测试身份(例如id(a) == id(b)
),而==
将测试是否相等(例如a.__eq__(b)
)。当我在IDLE中测试它时,它的功能是一样的,但这不是一个好习惯。这里有一个关于它的详细信息:How is the 'is' keyword implemented in Python?
如果你要处理的不同级别的字典,你可以使用类似:
def test_dict_for_key(dictionary, key, function):
for test_key, value in dictionary.items():
if key == test_key:
dictionary[key] = type(value)(map(function, value))
if isinstance(value, dict):
test_dict_for_key(value, key, function)
使用示例可能是这样的:
myDict = {
1: {
"a": "something",
"b": [0, 1, 2],
"c": ["a", "b", "c"]
},
2: {
"a": "somethingElse",
"b": [3, 4, 5],
"c": ["d", "e", "f"]
},
3: {
"a": "another",
"b": [6, 7, 8],
"c": ["g", "h", "i"]
}
}
# adds 1 to every entry in each b
test_dict_for_key(myDict, "b", lambda x: x + 1)
# prints [1, 2, 3]
print(myDict[1]["b"])
+0
很多答案我的所有问题,谢谢! – Mico
答
可以进行一些修复。
- 不要比较两个字符串(
if key is "b":
) - 当简单的说
print(item)
而是采用.format()
使用is
,因为你只有那你打印一个变量,没有额外的字符串格式化
修改后的代码:
for id, obj in myDict.items():
for key, val in obj.items():
if key == "b":
for item in val:
print(item)
答
如果确定你会在每种情况下都有一个b
密钥,你可以简单地做:
for id, obj in myDict.items():
for item in obj["b"]:
print item
答
我是发电机表达式的粉丝。
inner_lists = (inner_dict['b'] for inner_dict in myDict.values())
# if 'b' is not guaranteed to exist,
# replace inner_dict['b'] with inner_dict.get('b', [])
items = (item for ls in inner_lists for item in ls)
现在你可以使用一个foo
循环
for item in items:
# apply function
或map
transformed_items = map(func, items)
'如果key为 “B”',但怎么样' “C”'?他们也是名单。你不想要他们? – gil
@gill我不需要“c”。我只需要“b”中的值,因为我需要为列表中的每个值应用一些函数。 – Mico