In python, append dictionary value with each element in array
If you want to append an entire list to an existing list, you can just use extend()
:
a = [4,5,6]
d = {'index': [1,2,3]}
d['index'].extend(a)
output:
{'index': [1, 2, 3, 4, 5, 6]}
If you want to end up with a list containing two lists, [1,2,3] and [4,5,6], then you should consider how the dictionary value is initially created. You can do:
d['index'] = [1,2,3]
d['index'] = [d['index']]
d['index'].append([4,5,6])
output:
{'index': [[1, 2, 3], [4, 5, 6]]}
Python add list of objects as dict value
You can do this in one simple line:
message['data'].extend({'text': t, 'value': n} for t, n in my_list)
The generator expression creates a sequence of the desired dict
values, and extend
appends them to message['data']
one at a time.
How to add values of a key without losing any value in dictionary python when merging two list as dictionary?
Try this:
name = ['A', 'A', 'B', 'B', 'C', 'D', 'D', 'D']
num = [10, 20, 30, 40, 50, 60, 70, 80]
dict = {}
for key, value in zip(name, num):
if key not in dict:
dict[key] = value
else:
dict[key] += value
print(dict)
Adding items to Array as a Dictionary Value
You can use reduce(into:)
method (Swift4) and as follow:
let contacts = ["Aaron", "Adam", "Brian", "Brittany", ""]
let dictionary = contacts.reduce(into: [String:[String]]()) { result, element in
// make sure there is at least one letter in your string else return
guard let first = element.first else { return }
// create a string with that initial
let initial = String(first)
// initialize an array with one element or add another element to the existing value
result[initial] = (result[initial] ?? []) + [element]
}
print(dictionary) // ["B": ["Brian", "Brittany"], "A": ["Aaron", "Adam"]]
If you are using Swift3 or earlier you would need to create a mutable result dictionary inside the closure:
let contacts = ["Aaron", "Adam", "Brian", "Brittany", ""]
let dictionary = contacts.reduce([String:[String]]()) { result, element in
var result = result
guard let first = element.first else { return result }
let initial = String(first)
result[initial] = (result[initial] ?? []) + [element]
return result
}
print(dictionary) // ["B": ["Brian", "Brittany"], "A": ["Aaron", "Adam"]]
Note that the result is not sorted. A dictionary is an unordered collection. If you need to sort your dictionary and return an array of (key, Value) tuples you can use sorted by key as follow:
let sorted = dictionary.sorted {$0.key < $1.key}
print(sorted)
"[(key: "A", value: ["Aaron", "Adam"]), (key: "B", value: ["Brian", "Brittany"])]\n"
Python dictionaries - appending arrays to a dictionary for a specific key.
This is an expansion of the first answerer and my comment to the first answerer.
If I have the following arrays:
array1 = [1,2,3,4]
array2 = [2,6,27,1]
array3 = [6,1,2,3]
array4 = [7,1,2,6]
array5 = [8,2,1,6]
array6 = [3,4,1,1]
My dictionary is the following:
from collections import defaultdict
my_dict = defaultdict(list)
Now I will append the following arrays for different keys:
my_dict[1].append(array1)
my_dict[1].append(array2)
my_dict[1].append(array3)
my_dict[2].append(array4)
my_dict[3].append(array5)
my_dict[3].append(array6)
my_dict's contents
{1:[[1,2,3,4],[2,6,27,1],[6,1,2,3]], 2:[[7,1,2,6]], 3:[[8,2,1,6],[3,4,1,1]] }
To get the array associated with key = 1
foo = my_dict[1]
foo
[[1,2,3,4],[2,6,27,1],[6,1,2,3]]
Now to get the 3rd column of data:
import numpy as np #Need to use it to convert to array and float later on
foo = np.array(foo);# Have to convert it to an array
doo = foo[:,2]
doo
[3,27,2]
Now there may be situations where your array may be a mix of string and float or integer such that all elements in the array are string.
foo
[['1','2','3','4'],['2','6','27','1'],['6','1','2','3']]
foo = np.float32(foo)
foo
[[1.,2.,3.,4.],[2.,6.,27.,1.],[6.,1.,2.,3.]]
Conclusion: We can append arrays to a dictionary for a specific key using the defaultdict. Also subsets of the selected matrix can be extracted via normal column selection method. If the array associated with the key contains string elements, we can convert the data to numpy.float32, say or wherever we need to do computation with numbers.
Thank you,
Anthony of Sydney
Add items to Array in Dictionary
Thank you very much for your assistance (@Ron Rosenfeld)!
Below is my final code part.
For i = LBound(arr) To UBound(arr)
If d.Exists(arr(i, 3)) Then
d(arr(i, 3)) = d.Item(arr(i, 3)) & "," & arr(i, 1)
Else
d.Add Key:=arr(i, 3), Item:=arr(i, 1)
End If
Next i
I was still testing whether I should concatenate the strings with & "," &
or with the JOIN()
function but decided eventually for the first option.
Regarding my array size, I added a row counter to fit the length of the array. lrow = sh1.Cells(Rows.count, "D").End(xlUp).Row
.
Swift - Adding value to an array inside a dictionary
EDIT: Thanks to Martin's comment. The snippet below is the the most succinct answer I can think of. I was initially coming at it from a wrong direction. and I was getting an error. See comments
struct Student {
let id: Int
let subject : String
}
var studentArray = [Student(id: 1, subject: "History"), Student(id: 2, subject: "History"), Student(id:1, subject: "Maths")]
typealias Subject = String
var dict : [Int: [Subject]] = [:]
for student in studentArray {
(dict[student.id, default: []]).append(student.subject)
}
print(dict)
Previous answers:
struct Student {
let id: Int
let subject : String
}
var studentArray = [Student(id: 1, subject: "History"), Student(id: 2, subject: "History"), Student(id:1, subject: "Maths")]
typealias Subject = String
var dict : [Int: [Subject]] = [:]
for student in studentArray {
var subjects = dict[student.id] ?? [String]()
subjects.append(student.subject)
dict[student.id] = subjects
}
print(dict)
Or you can do it this way:
struct Student {
let id: Int
let subject : String
}
var studentArray = [Student(id: 1, subject: "History"), Student(id: 2, subject: "History"), Student(id:1, subject: "Maths")]
typealias Subject = String
var dict : [Int: [Subject]] = [:]
for student in studentArray {
if let _ = dict[student.id]{
dict[student.id]!.append(student.subject)
}else{
dict[student.id] = [student.subject]
}
}
print(dict)
whichever you like
Related Topics
How to Load My Own Reality Composer Scene into Realitykit
Map and Flatmap Difference in Optional Unwrapping in Swift 1.2
Why Do Integers Not Conform to the Anyobject Protocol
How to Read a Property List from Data in Swift 3
Getting a Let Value Outside a Function
Save & Retrieve Tableviewcell Checkmark Using Nsuserdefaults in Swift
A Switch Bug in Swift? - "Switch Must Be Exhaustive, Consider Adding a Default Clause."
Swift Protocol Implements Equatable
iOS - Add Image and Text in Title of Navigation Bar
How to Link to a 3Rd Party Swift Framework
How to Request a Desktop Version of a Webpage Using Uiwebview in Swift 3.0
How to Implement iOS 11's Mkusertrackingbutton
Iphonex Not Call Prefersstatusbarhidden
Animating a Navigation Bar Color