我仍然是Python
的新手,目前正在尝试使用dictionaries
进行操作。我有一个嵌套的dictionary
,看起来像这样:
nestedDic = {'FROM': {'SOME TEXT FROM': ['CHILD1', 'CHILD2']}}
并且我能够通过遍历子节点来打印它们。
def print_nested(val, nesting = -5):
if type(val) == dict:
#print('')
nesting += 5
for k in val:
print(end='')
print(k)
print_nested(val[k],nesting)
else:
print(val)
但是输出看起来像:
但是我需要的输出是:
从CHILD1 CHILD2读一些文本
我要去哪里错了?任何帮助都将不胜感激。
答案 0 :(得分:3)
这应该完成您的工作:
nestedDict = {'FROM': {'SOME TEXT FROM': ['CHILD1', 'CHILD2']}}
def printDict(inDict):
print(k,end=" ")
for k,v in inDict.items():
if type(v) == dict:
printDict(v)
elif type(v) == list:
for i in v:
print(i, end=" ")
else:
print(v, end=" ")
输出:
FROM SOME TEXT FROM CHILD1 CHILD2
答案 1 :(得分:2)
您想要print(end=' '); print(k)
而不是print(k, end=' ')
。在调用函数时像这样更改kwarg不会使它们在下次调用时设置。
答案 2 :(得分:1)
def printNestedDict(d: dict):
for k, v in d.items():
if (isinstance(v, dict)):
print(k, end = " ")
printNestedDict(v)
continue
if (any(isinstance(v, t) for t in [tuple, list])):
print(k, *v, sep = " ", end = " ")
continue
print(k, v, sep = " ", end = " ")
完全按照您的预期进行,检查集合并输出每个集合。
答案 3 :(得分:1)
@Kulasangar ,您的问题非常有趣而且很好。我想使用递归解决您的问题。
它与您提供的嵌套输入字典以及包含其他数据结构(例如列表,元组,设置, int ,浮动等
我想如果您将拥有 int ,浮动,复杂,长,元组作为键,如果将具有 set , list , tuple 之类的相应值作为相应值的项目,该怎么办?>
设置和字典是无序类型,因此最好将它们的长度限制为1个项目。这就是为什么我将它们的长度限制为1以按顺序获得最终字符串的单词的原因。
例如。以下 INPUT 词典。
nestedDic = {
('DATA', 'ANALYSIS'): {'IS': {'VERY': {'VERY': ['IMPORTANT.']}}},
4+4j: ['IS', ('A', 'Complex', 'number.')],
3.14: {
'IS': {'VALUE': {
'OF PI': {
'(A MATHEMATICAL': ['CONSTANT).']
}
}
}
},
1729: ['IS', 'KNOWN', ('AS', ('RAMANUJAN NUMBER.'))], # sets can only contain immutable values
'I AM RISHIKESH': {
'AGRAWANI.': 'A GREAT FAN',
('OF', 'PYTHON'): (' AND MATHEMATICS.', {'I WAS BORN ON'}),
1992: 'AND I LIKE THIS YEAR.'
}
}
您期望以下字符串为 OUTPUT 。
DATA ANALYSIS IS VERY VERY IMPORTANT. (4+4j) IS A Complex number. 3.14 IS VALUE OF PI (A MATHEMATICAL CONSTANT). 1729 IS KNOWN AS RAMANUJAN NUMBER. I AM RISHIKESH AGRAWANI. A GREAT FAN OF PYTHON AND MATHEMATICS. I WAS BORN ON 1992 AND I LIKE THIS YEAR.
现在,请看下面的Python代码。这里我有2个递归函数。
get_string()适用于列表,元组和设置。如果字典的键是元组,也可以使用。
get_string_from_nested_dict()递归创建一个字符串。如果它找到任何键为 tuple ,那么它将调用另一个递归函数 get_string()以获取确切的单词字符串(而不是使用元组本身)。
def get_string(l):
s = ''
for elem in l:
if type(elem) is str:
s += elem + ' '
elif type(elem) is tuple or type(elem) is list or type(elem) is set: # tuple, list, set
s += get_string(elem) + ' '
else: # int,float, complex, long
s += str(s) + ' '
return s.strip() # Remove leading or trailing white spaces
def get_string_from_nested_dict(nestedDic):
s = ''
for key in nestedDic:
if s is str:
s += key + ' '
elif type(key) is tuple:
s += get_string(key) + ' '
else: # int, complex, float, long
s += str(key) + ' '
item = nestedDic[key]
if type(item) is dict: # dict
s += get_string_from_nested_dict(nestedDic[key]) + ' '
elif type(item) is tuple or type(item) is list or type(item) is set: # list, tuple, set
s2 = get_string(item)
s += s2 + ' '
else: # int, float, comples, long
s += str(item) + ' '
return s.strip() # Remove leading or trailing white spaces
# Start
if __name__ == "__main__":
# *** TEST CASE 1 ***
nestedDic = {'FROM': {'SOME TEXT FROM': ['CHILD1', 'CHILD2']}}
s = get_string_from_nested_dict(nestedDic)
print(s, '\n') # FROM SOME TEXT FROM CHILD1 CHILD2
# *** TEST CASE 2 ***
nestedDic2 = {'HELLO,': {
'IT IS': ['VERY', {'NICE', 'PROGRAM.'}],
'PYTHON': {'IS', 'SUPER.'},
'YOU': ('CAN USE IT', 'FOR', ['DATA SCIENCE.'])
}
}
s2 = get_string_from_nested_dict(nestedDic2)
print(s2, '\n')
# *** TEST CASE 3 ***
nestedDic3 = {
('DATA', 'ANALYSIS'): {'IS': {'VERY': {'VERY': ['IMPORTANT.']}}},
4+4j: ['IS', ('A', 'Complex', 'number.')],
3.14: {
'IS': {'VALUE': {
'OF PI': {
'(A MATHEMATICAL': ['CONSTANT).']
}
}
}
},
1729: ['IS', 'KNOWN', ('AS', ('RAMANUJAN NUMBER.'))], # sets can only contain immutable values
'I AM RISHIKESH': {
'AGRAWANI.': 'A GREAT FAN',
('OF', 'PYTHON'): (' AND MATHEMATICS.', {'I WAS BORN ON'}),
1992: 'AND I LIKE THIS YEAR.'
}
}
s3 = get_string_from_nested_dict(nestedDic3)
print(s3)
答案 4 :(得分:0)
这是一种可能的解决方案,但仅在像您这样的情况下有效:
output = []
def print_nested(val):
if type(val) == dict:
for k, v in val.items():
output.append(k)
print_nested(v)
elif type(val) == list:
for k in val:
output.append(k)
print_nested(k)
nestedDic = {'FROM': {'SOME TEXT FROM': ['CHILD1', 'CHILD']}}
print_nested(nestedDic)
output = " ".join(output)
print(output)