【发布时间】:2017-12-20 20:55:38
【问题描述】:
我正在尝试对包含字典列表和Python 3.6 中的其他数据的字典进行排序和比较。我不确定比较两者的最佳方法。两个字典中的数据是一样的,但是我无法控制它们给出的顺序。数据如下所示:
dict_A = {
'addresses': [
{'address': 'Tribal Land', 'address_country': 'AB', 'city': None, 'postal_code': None, 'state': 'GY'},
{'address': 'Userland', 'address_country': 'ND', 'city': None, 'postal_code': None, 'state': 'KY'}],
'name': 'FooBar',
'dob': None,
'ids':[
{'date': None, 'country': None, 'number': 'Male', 'type': 'Gender', 'location': 'USA'},
{'date': None, 'country': 'VE', 'number': '1234567', 'type': 'Foo No.', 'location': 'USA'}]
}
dict_B = {
'addresses': [
{'address': 'Userland', 'address_country': 'ND', 'city': None, 'postal_code': None, 'state': 'KY'},
{'address': 'Tribal Land', 'address_country': 'AB', 'city': None, 'postal_code': None, 'state': 'GY'}],
'dob': None,
'id':[
{'country': 'VE', 'date': None, 'type': 'Foo No.', 'location': 'USA', 'number': '1234567'},
{'country': None, 'date': None, 'type': 'Gender', 'location': 'USA', 'number': 'Male'}],
'name': 'FooBar'
}
我正在尝试与评估为 True 的 dict_A == dict_B 进行比较。
我尝试遍历字典,将项目发送给 Pandas 并将 dict 设置为 ordered_dict,但这似乎不起作用。我不确定最好的方法。
# Loop over data, and conver the list of dicts to data frame for sorting,
# then take the data, once sorted, and put it back into list of dicts
for key, val in dict_A.items():
if type(val) is list:
val.sort(key=lambda x: x if isinstance(x, str) else "")
dataframe = pd.DataFrame(val, index=range(len(val)))
dataframe.sort_values(by=dataframe.columns[0])
new_val = [OrderedDict(row) for i, row in dataframe.iterrows()]
dict_A.update({key: new_val})
也许更好的方法是将字典设置为列表,然后以这种方式进行比较?
【问题讨论】:
-
键/值对没有多大意义:
'number': 'Male'、'type': 'Gender'、'country': None、'location': 'USA'。 -
可能是他当场制作的随机数据?我会建议 Mockaroo 处理这种事情。
-
@srig,这是我虚构的数据。最终只是为了举例
-
当您知道它们之间的唯一区别是列表不遵循顺序时,为什么还要尝试对它们进行排序?
-
我想比较两个数据集。如果不是很明显,上面的数据是人为的,但我正在比较的真实数据具有类似的嵌套数据结构。我正在将一组已知数据与来自 API 的一组未知数据进行比较。有时会有匹配,有时会有不同的数据。我需要知道那是什么时候。
标签: python python-3.x list sorting dictionary