使用 flatMapValues 时 pyspark 中的键错误

问题描述

我想添加在 flatMapValues 中使用的“键”,但我总是弄错。

这是rdd.collect()

[{'a': 1,'b': 2,'c': [1,2,3,4]},{'a': 11,'b': 22,'c': [5,6,7,8]},'b': 23,8]}]

和操作是

def add_key(x):
     x[0]['key'] = x[1]
     return x
rdd.map(lambda x: (x,x['c'])).flatMapValues(lambda x: x).map(add_key).map(lambda x:(x[1],x[0])

但我得到的结果是

[(1,{'a': 1,4],'key': 1}),(2,'key': 3}),(3,(4,'key': 4}),(5,8],'key': 5}),(6,'key': 7}),(7,(8,'key': 8}),'key': 8})]

如果'key'部分错误,结果应该是

[(1,'key': 2}),'key': 6}),'key': 8})]

1

解决方法

这是一个我不明白的有趣(错误?)。但这里有一个替代方案,应该会产生预期的结果:

rdd2 = (rdd
    .map(lambda x: (x,x['c']))
    .flatMapValues(lambda x: x)
    .map(lambda x: (x[1],{**x[0],**{'key':x[1]}}))
)

rdd2.collect()
[(1,{'a': 1,'b': 2,'c': [1,2,3,4],'key': 1}),(2,'key': 2}),(3,'key': 3}),(4,'key': 4}),(5,{'a': 11,'b': 22,'c': [5,6,7,8],'key': 5}),(6,'key': 6}),(7,'key': 7}),(8,'key': 8}),'b': 23,'key': 8})]