使用 .join() 操作嵌套字典的内部字典元素

Use .join() to manipulate inner dictionary elements of a nested dictionary

我有一个问题。我试图将其他问题的信息放在一起,但没有成功。 假设我有以下格式的数据:

file_list = ["f1", "f2", "f3"]
inner_dict = {1: "one", 2: "two", 3: "three"}
outer_dict = {}

for f in file_list:
     outer_dict[f] = inner_dict

我的目标是通过以下方式打印(保存到文件中):

f1, 1, one
f1, 2, two
f1, 3, three
f2, 1, one
f2, 2, two
f2, 3, three
f3, 1, one
f3, 2, two
f3, 3, three

为此,我开始关注 outer_dict 的项目,并设法将它们分开打印,但我不确定如何进一步加入(更重要的是,如果这是最直接走)。

for key, value in outer_dict.items():
    inn_keys = value.keys()
    inn_values = value.values()
    b1 = "\n".join([str(x) for x in inn_keys] )
    b2 = "\n".join([str(x) for x in inn_values] )

感谢您的任何建议。

你可以这样做:

string_list = []

for el1 in file_list:
    for el2 in inner_dict.items():
        string_list.append(", ".join([el1, str(el2[0]), el2[1]]))

print(string_list)

输出:

['f1, 1, one', 
 'f1, 2, two', 
 'f1, 3, three', 
 'f2, 1, one', 
 'f2, 2, two', 
 'f2, 3, three', 
 'f3, 1, one', 
 'f3, 2, two',
 'f3, 3, three']

修补您的代码以使其正常工作看起来像这样:

b1 = ""
for key, value in outer_dict.items():
    b1 += "\n".join([','.join([key,str(k),v]) for k, v in value.items()]) + '\n'

但是,我认为你做的比 python 中应该做的要复杂得多,一个更简单的解决方案是使用嵌套循环:

s = ""
for f in file_list:
    for k,v in inner_dict.items():
        s+= ','.join([f,str(k),v]) + "\n"

我相信你能想出一个可以为你做到这一点的单线。

join可以用在你的情况下,记得把你的ints转换成str:

print '\n'.join([', '.join([e1] + [str(e) for e in e2]) for e1, e2 in zip(file_list, inner_dict.items())])

f1, 1, one
f2, 2, two
f3, 3, three

这个 oneliner 怎么样 - 只需连接元组(即 [(i,)+j for j in inner_dict.items() for i in file_list])并将元组列表展平为一个简单列表。

[item for sublist in [(i,)+j for j in inner_dict.items() for i in file_list] for item in sublist]

输出-

['f1', 1, 'one', 'f2', 1, 'one', 'f3', 1, 'one', 'f1', 2, 'two', 'f2', 2, 'two', 'f3', 2, 'two', 'f1', 3, 'three', 'f2', 3, 'three', 'f3', 3, 'three']

N.B。如果使用字典维护顺序,最好使用 OrderedDict

似乎其他答案在字典中假定了确定性顺序。但是字典do not have a deterministic order。其实可以在Python中设置hash_randomization 2.命令行选项-R:

启动即可
python -R

这是default in Python 3

因此,为了使这项工作更可靠,并且 Python 3,对内部字典的键进行排序。由于它被多次使用,因此只对它进行一次排序并在文件列表的所有迭代中重新使用它:

from __future__ import print_function

file_list = ["f1", "f2", "f3"]
inner_dict = {1: "one", 2: "two", 3: "three"}

inner_list = [', '.join([str(key), inner_dict[key]]) for key in sorted(inner_dict)]

for fname in file_list:
    for inner in inner_list:
        print('{}, {}'.format(fname, inner))

输出:

f1, 1, one
f1, 2, two
f1, 3, three
f2, 1, one
f2, 2, two
f2, 3, three
f3, 1, one
f3, 2, two
f3, 3, three

既然您想将其保存为 csv 文件,请查看这是否有帮助。如果顺序很重要,您可以使用 OrderedDict

from collections import OrderedDict
import csv


file_list = ["f1", "f2", "f3"]
inner_dict = {1: "one", 2: "two", 3: "three"}
outer_dict = OrderedDict()

for f in file_list:
    outer_dict[f] = inner_dict

rows = []
for i,k in outer_dict.items():
    for m,n in k.items():
        rows += [[str(x) for x in [i, m, n]]]

with open('test.csv', 'w') as f:
    _csv = csv.writer(f, escapechar=' ', quoting=csv.QUOTE_NONE)
    [_csv.writerow(row) for row in rows]

test.csv 文件看起来是这样的:

f1,1,one
f1,2,two
f1,3,three
f2,1,one
f2,2,two
f2,3,three
f3,1,one
f3,2,two
f3,3,three