字典操作

Golang

// map删除
m := map[string]int{"test": 1, "test2": 2}
delete(m, "test")
// map合并
func mapMege(list ...map[string]int) map[string]int {
	n := make(map[string]int)
	for _, m := range list {
		for k, v := range m {
			n[k] = v
		}
	}
	return n
}
// map排序
func mapSort(m map[string]int) map[string]int {
	s := make([]string, 0)
	for k, _ := range m {
		s = append(s, k)
	}
	sort.Strings(s)

	n := make(map[string]int)
	for _, k := range s {
		n[k] = m[k]
	}

	return n
}

Nodejs

// 对象删除
const m = {test: 1, test2: 2}
delete m['test']
// 对象合并
const m1 = {test1: 1}
const m2 = {test2: 2}
const mm = Object.assign(m1, m2)
// const mm = {...m1, ...m2}
// 对象排序
const m = {test2: 2, test1: 1, test3: 3}
// 按照key排序,可忽略sort参数,默认升序
const s = Object.keys(m).sort((i, j)=> m[i]-m[j])
// 原样输出对象key,就用[]
const n = s.map(k => ({[k]: m[k]}));

Python

// 字典删除
m = {"test": 1, "test2": 2}
del m["test"]
// 字典合并
m = {"test": 1}
m2 = {"test2": 2}
m.update(m2)
// 字典排序
m = {"test2": 2, "test1": 1, "test3": 3}
mm = dict(sorted(m.items(), key=lambda x: x[0], reverse=False))

C#

// 字典删除
Dictionary<string, int> m = new Dictionary<string, int>() {{"test", 1},{"test2", 2}};
m.Remove("test2");
foreach (var kvp in m) Console.WriteLine(kvp.Key, kvp.Key);
// 字典合并
Dictionary<string, int> m = new Dictionary<string, int>(){{"test", 1}};
Dictionary<string, int> m2 = new Dictionary<string, int>(){{"test2", 2}};
var mm = m.Union(m2).ToDictionary(k => k.Key, v => v.Value);
// 字典排序
Dictionary<string, int> m = new Dictionary<string, int>(){{"test"1},{"test3", 3},{"test2", 2}};
var n = m.OrderBy(o => o.Key).ToDictionary(k=>k.Key, v=>v.Value);
posted @ 2022-08-26 23:21  codeIsArt  阅读(18)  评论(0编辑  收藏  举报