相关疑难解决方法(0)

将OrderedDict转换为正常的dict保留顺序?

如何OrderedDict在保留相同顺序的同时将转换为普通字典?

我问这个的原因是因为当我从API获取数据时,我得到一个JSON字符串,我用它json.loads(str)来返回一个字典.返回的这个字典json.loads(...)只是乱序,随机排序.另外,我读过这个OrderedDict工作很慢,所以我想使用与原始JSON字符串相同顺序的常规字典.

稍微偏离主题:无论如何都要将JSON字符串转换为dict,json.loads(...)同时保持相同的顺序而不使用collections.OrderedDict

python string json dictionary ordereddictionary

0
推荐指数
1
解决办法
3041
查看次数

如何在Python中维护JSON转储中的字典元素顺序

由于本网站上非常有帮助的人,我已经能够整合一个脚本,该脚本获取用户名(由用户输入),然后使用循环将每个用户名附加到特定的JSON结构.但是,我注意到我的JSON转储中的顺序没有得到维护.例如,这是我的循环和JSON转储的样子:

list_users = []
for user in users:
    list_users.append({"name": user,
                       "member": 123,
                       "comment": "this is a comment"})

json_user_list_encoding = json.dumps(list_users, indent=2)
Run Code Online (Sandbox Code Playgroud)

我的打印看起来像这样:

({"member": 123,
  "comment": "this is a comment"
  "name": user
  })
Run Code Online (Sandbox Code Playgroud)

我想知道当我使用JSON转储时是否可以在"list_users"中维护相同的顺序.我已经看了一下这个网站,根据我的阅读,我将不得不分配密钥以维持特定的订单.但是,我不知道如何做到这一点,因为我只有一个JSON对象.我希望这是有道理的.谢谢您的帮助.

python json

0
推荐指数
1
解决办法
2573
查看次数

迭代列表对象的JSON结构并查找下一个键

我有一个Json列表,我想从给定的键打印所有键,直到字典结束.但是我写的代码非常复杂.如何以较低的复杂性做到这一点?我正在使用Python 3

dictionary = [{"a": "1"}, {"b": "2"}, {"c": "3"}, {"d": "4"}]

try:
    for token in dictionary:
            if "b" in list(token.keys())[0]:
                new_dict = dictionary[len(list(token.keys())[0]):]
                for i in new_dict:
                    print(new_dict[len(list(i.keys())[0]):])
                break
            else:
                print("Inception")
except Exception as error:
    print(str(error))
Run Code Online (Sandbox Code Playgroud)

希望
输入:b
输出:c,d

我的输出:

Inception
[{'c': '3'}, {'d': '4'}]
[{'c': '3'}, {'d': '4'}]
[{'c': '3'}, {'d': '4'}]
Run Code Online (Sandbox Code Playgroud)

python json dictionary python-3.x

0
推荐指数
1
解决办法
103
查看次数

Python 3.6+:具有相同键但顺序不同的两个字典的相等性

对于两个字典d1d2定义为

d1 = {'foo':123, 'bar':789}
d2 = {'bar':789, 'foo':123}
Run Code Online (Sandbox Code Playgroud)

键的顺序在Python 3.6+中保留。当我们遍历字典并打印项目时,这一点很明显。

>>> for x in d1.items():
...     print(x)
...
('foo', 123)
('bar', 789)


>>> for x in d2.items():
...     print(x)
...
('bar', 789)
('foo', 123)
Run Code Online (Sandbox Code Playgroud)

为什么Python仍然考虑d1d2保持平等?

>>> d1 == d2
True
Run Code Online (Sandbox Code Playgroud)

python

0
推荐指数
1
解决办法
38
查看次数

为什么使用 std::unordered_map 的 C++ 实现比使用字典的等效 Python 实现慢得多?

为此,我使用坐标变换 (x,y)-> 1000*x+y 来提高效率。

了解代码的作用并不是很重要,但对于这个问题来说: https: //oeis.org/A337663

这只是将它们添加到板上,然后将它们作为性能指标删除:

##################

#1###1###1###1###1#

##################

并记录接触棋盘上数字的邻居的总和

#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <ctime>

using namespace std;
//I Know this is bad practice, but just for readability for now

void add_update_edges_and_used(int spot, unordered_map<int, unordered_set<int> > &edge_sums_to_locations, unordered_map<int, int> &edge_locations_to_sums,
                               unordered_set<int> &used_locations, int current_number) {
    used_locations.insert(spot);

    vector<int> neighbors { spot+1000,spot-1000,
                            spot+1,spot-1,
                            spot+1000+1,spot-1000+1,
                            spot+1000-1,spot-1000-1 };

    for (int neighbor : neighbors) {
        if (used_locations.count(neighbor) == 0) {
            if (edge_locations_to_sums.count(neighbor)) {
                edge_sums_to_locations.at(edge_locations_to_sums.at(neighbor)).erase(neighbor);
                edge_locations_to_sums.at(neighbor) += current_number;
            } …
Run Code Online (Sandbox Code Playgroud)

c++ python performance

0
推荐指数
1
解决办法
540
查看次数

订购dict默认?

是否有可能使默认的dict文字创建有序的dicts而不是无序的?

我想键入复杂的嵌套配置,如:

config = {
   'train': {
       'speed': 0.001,
       'initial_values': [1, 2, 3]
   },
   'model': {
...
   }
}
Run Code Online (Sandbox Code Playgroud)

并且想要写一堆括号

config = OrderedDict([(
    'train', OrderedDict([(
       'speed', 0.001), (
       'initial_values', [1, 2, 3])]),(
    'model', OrderedDict([(
...
Run Code Online (Sandbox Code Playgroud)

绝对是无法解决的.

关于为什么我的愿望不好,请不要有哲学.


好的,目前我会写一些像:

def od(*args):
   return OrderedDict([(args[i], args[i+1]) for i in range(0, len(args), 2)])

config = od(
    'train', od(
        'speed', 0.001,
        'initial_values', [1, 2, 3]
     ),
     'model', od(
    ...
     )
)
Run Code Online (Sandbox Code Playgroud)

python dictionary ordereddictionary literals

-1
推荐指数
1
解决办法
337
查看次数

如何从条件中获取带有条件的排序列表?

所以我在(Python 3.x)中有这个字典:

dict = {
    "Gryffindor": gryffcount,
    "Ravenclaw": ravencount,
    "Hufflepuff": hufflecount,
    "Slytherin": slycount
}
Run Code Online (Sandbox Code Playgroud)

gryffcount,ravencount,hufflecountslycountint变量.

我想输出中的列表: - 第一个项目应是该值最高的关键 - 第二个应该是其值第二高的关键 - 等等...编辑:但是如果两个计数相等,那么字典中首先提到的那个应该首先出现.

所以如果gryffcount == 0,ravencount == 2,hufflecount == 0,slycount == 4

我应该得到这个清单:

["Slytherin","Ravenclaw","Gryffindor","Hufflepuff"]
Run Code Online (Sandbox Code Playgroud)

python python-3.x

-2
推荐指数
1
解决办法
56
查看次数