Convert [key1,val1,key2,val2] to a dict?
b = dict(zip(a[::2], a[1::2]))
If a
is large, you will probably want to do something like the following, which doesn't make any temporary lists like the above.
from itertools import izip
i = iter(a)
b = dict(izip(i, i))
In Python 3 you could also use a dict comprehension, but ironically I think the simplest way to do it will be with range()
and len()
, which would normally be a code smell.
b = {a[i]: a[i+1] for i in range(0, len(a), 2)}
So the iter()/izip()
method is still probably the most Pythonic in Python 3, although as EOL notes in a comment, zip()
is already lazy in Python 3 so you don't need izip()
.
i = iter(a)
b = dict(zip(i, i))
In Python 3.8 and later you can write this on one line using the "walrus" operator (:=
):
b = dict(zip(i := iter(a), i))
Otherwise you'd need to use a semicolon to get it on one line.
Convert list pairwise to dictionaries?
zip
and a list comprehension are the way to go:
>>> a = ["a","b","c","d","e","f"]
>>> [{'key': k, 'value': v} for k, v in zip(a[::2], a[1::2])]
[{'value': 'b', 'key': 'a'}, {'value': 'd', 'key': 'c'}, {'value': 'f', 'key': 'e'}]
Notice how the list is sliced with a step of two starting at 0 and 1 and then zipped.
Covert String to Key-Value Pair or JSON in dart
Okay, this is just a fast horrible hacky solution which can with high probability be improved. But I hope it gets closer to a solution for you:
import 'dart:convert';
void main() {
var str =
"[{key1: 0.1, key2: 0.2}, {key1: 0.3, key2: 0.4}, {key1: 0.5, key2: 0.6}]";
str = str.replaceAll(' ', '').replaceAllMapped(
RegExp(r'([\{,])([a-zA-Z0-9]+)(:)'),
(match) => '${match[1]}"${match[2]}"${match[3]}');
print(str);
// [{"key1":0.1,"key2":0.2},{"key1":0.3,"key2":0.4},{"key1":0.5,"key2":0.6}]
final jsonObject = jsonDecode(str) as List<dynamic>;
jsonObject.forEach(print);
// {key1: 0.1, key2: 0.2}
// {key1: 0.3, key2: 0.4}
// {key1: 0.5, key2: 0.6}
}
Convert string with alternating key value pairs to a dictionary
Simple answer.
a = "key1\\val1\\key2\\val2\\key3\\val3"
b = a.split('\\')
dc = {}
for i in range(0,len(b), 2):
dc[b[i]]=b[i+1]
convert string to dictionary in swift 5?
you may have to do it the hard way. Something like this:
import SwiftUI
@main
struct TestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
extension String {
func trim() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
struct ContentView: View {
var body: some View {
Text("testing")
.onAppear {
let myString: String = "{key1: val1, key2: val2, key3: val3}"
let myJson = transform(myString)
print("----> myJson: \(myJson)")
}
}
func transform(_ myString: String) -> [String : String] {
var result = [String : String]()
if myString.count > 2 { // case of {}
let temp1 = myString.dropFirst().dropLast()
let temp2 = temp1.split(separator: ",").map{String($0)}
for str in temp2 {
let temp3 = str.split(separator: ":").map{String($0)}
let (k,v) = (temp3[0].trim(),temp3[1].trim())
result[k] = v
}
}
return result
}
}
Related Topics
Saving an Object (Data Persistence)
How to Check If a List Is Empty
Does Python Have "Private" Variables in Classes
How to Play an Mp3 With Pygame
Installing Python Module Within Code
Remove All the Elements That Occur in One List from Another
How to Add a New Column to an Existing Dataframe
How to Call a Function Within a Class
Split String With Multiple Delimiters in Python
Are For-Loops in Pandas Really Bad? When Should I Care
What Is the _Del_ Method and How to Call It
Why Is This Printing 'None' in the Output
How to Find All Matches to a Regular Expression in Python