Questions tagged [dictionary]

19768 questions
1

votes
1

answer
269

Views

python pandas non-unique dict keys

I have an Excel file with data like this Fruits Description oranges This is an orange apples This is an apple oranges This is also oranges plum this is a plum plum th...
jumpman8947
1

votes
1

answer
499

Views

Swift - Is There A “Dictionary With Duplicate Keys” Workaround?

Currently I am working with alamofire to send post requests to a certain site. In the paramaters of the post request, there is a duplicate key entry that is required to send the post request, but when I am making the dictionary and enter both keys as string literals, I receive the nasty 'Duplicate K...
David K
1

votes
1

answer
72

Views

Typescript: Define initial state for object using interface with dictionary of keys

I've defined my interface as follows: export interface FullCache { // keys names are dynamic [cacheId: string]?: SingleCache; } export interface SingleCache { data: string; } so an example FullCache object could look like this: { ca001:{data:'foo'}, ca002:{data:'bar'} } However, I can't figure out...
Our_Benefactors
1

votes
1

answer
150

Views

Python modifying dict entries in-place during iteration

I know that in the general case, it’s unsafe to mutate a dict while iterating over it: d = {1: 2, 3: 4} for k in d.keys(): d[k + 1] = d[k] + 1 This yields a RuntimeError as expected. However, while reading the documentation for dict, I found the following (emphasis mine): Iterating views while add...
Andrew Sun
1

votes
1

answer
348

Views

looping through a dictionary of dataframes in python

First of all, I wrote this function: def writing_in_excel(path, df, sheet_name): writer = pd.ExcelWriter(path, datetime_format='m/d/yyyy') df.to_excel(writer, sheet_name = sheet_name, index=False, freeze_panes = (0,1)) writer.save() writer.close() Then, I have a dictionary of dataframes: import pand...
Yun Tae Hwang
1

votes
3

answer
28

Views

Remove space in keys of a dictionary

d={'A ':[],'B '=[]} I want to remove the whitespace before the quote and produce the following: d={'A':[],'B'=[]} for k,v in d.items(): k=k.replace(' ','') pprint.pprint(d) I expect the above code to remove space before the quote,but the output is same as previous dictionary I also tried k=k.strip()...
Ganga
1

votes
1

answer
35

Views

Convert Multiple pandas Column into json

My dataframe df is like: col_1 col_2 col_3 A Product 1 B product 2 C Offer 1 D Product 1 What i want is to convert all this column to json with the condition that row of col_2 and col_1 should be key value pair. I have tried the following: df['col_1_2'] = df.apply(lambd...
sourav khanna
1

votes
2

answer
45

Views

Converting Map<key, value> to List<value>

I've been searching for a while without success. I am trying to convert a Map to a List (discarding key). Sure, I can do var addictionList = new List(); dataMan.forEach((String date, AddictionDay day) { addictionList.add(day); }); but is there a more straight approach, like var addictionList = dat...
Martin.
1

votes
2

answer
43

Views

Accessing swift dictionary members using AnyObject

I'm having trouble with understanding how to properly do unwrapping in Swift. Here is the situation: I have these two classes: class Alpha { var val: Int init(x: Int) { val = x } func doSomething() -> Int { // does stuff and returns an Int value return val } } and a second class which is a subclass...
fiend
1

votes
3

answer
57

Views

Getting average of scores from 2 different dictionaries in python

I have a Python3 code that return 2 dictionaries (both have same indices) the first dictionary contains list of names, the second contains list scores. for each of the indices the list might contain the name repeated and might contains different names as in the code below. how can i get for each ind...
EYakoumi
1

votes
2

answer
50

Views

Create a list of dictionaries with unique keys from a list of dictionaries with duplicated keys

I have a list of dictionaries: records = [{id:123, name:'Course A', enrolled_date:'1st Feb'}, {id:123, name:'Course A', enrolled_date:'1st Jan'}, {id:456, name:'Course B', enrolled_date:'1st Jan'}] I want to create a new list of dictionaries from this data. The new list should only contain diction...
Zak Smith-Sanga
1

votes
2

answer
56

Views

Combine part of geojson object into another in Python

EDIT: I am trying to manipulate JSON files in Python. In my data some polygons have multiple related information: coordinates (LineString) and area percent and area (Text and Area in Point), I want to combine them to a single JSON object. As an example, the data from files are as follows: data = { '...
ahbon
1

votes
2

answer
42

Views

How to add into map in range loop

package main import ( 'fmt' ) func main() { m := make(map[int]int, 4) m[1] = 0 m[2] = 0 for k, _ := range m { i := 10 + k m[i] = 0 } fmt.Println(m) fmt.Println('len:', len(m)) } This code returns: 8 or 10 or 6 as length of map after loop. Video is here, playgroud here. I see that new added elements...
Vladimir Kovpak
1

votes
4

answer
60

Views

How to create a dictionary to reverse lookup list items that each have sets?

I have test names in a list like this in Python v2.7: all_tests = ['test1', 'test2', 'test3', ..., 'testN'] And for each test name, I can lookup a set of properties that the test has: series['test'] = {'prop1', 'prop2', 'prop3', ..., 'propN'} E.g., series['test1'] = {'yellow', 'blue', 'orange'} seri...
WilliamKF
1

votes
2

answer
50

Views

How can I update a value in a dictionary in python?

I have a dictionary like this: my_dict = {key1:value1, key2:value2} I want to first check if some key exists if yes I have to convert the value of existing key into a list and add other value to that like this: my_dict = {key1:[value1,new_value], key2:value2} I mean just I need to update one key in...
Laya amiri rad
1

votes
2

answer
61

Views

extract values of column according to value in another columns in csv file

Here is my file: id;verbatim;score 0;1; je suis beau;1 1;2; je suis laid;0 2;3;je suis merveilleux;1 3;4;je suis repugne;0 I would like to extract all sentences in column 'verbatim' which have a score of 1 and all which have a score of 0 so that I have two separated files: print(verbatim, score =...
kely789456123
1

votes
1

answer
57

Views

Change the teams of some users

I have a dictionary that keeps a team name (string) and the users of the team (list). I want to change the teams of some users. My idea is to find the place of the user who we want to move and remove it from the current collection. Then add the user to the desired team. The problem is I can't find t...
Kaloyan K.
1

votes
2

answer
40

Views

Get a key: value pair dictionary from two consecutive columns of pandas dataframe

I am extracting data from excel sheet and storing it into a dataframe. I want to create a key:value pair dictionary from the columns of dataframe. For example: [{key=column1 : value = column2, key = column3 : value=column4 }], and so on till the last column. Here is the sample data on which I am wor...
Priyanka Lanjewar
1

votes
2

answer
48

Views

Create a dict whose values update every time its is used

I want to create a dictionary that updates its keys every time it is used What I have tried: import itertools changing_dict = { 'key1': next(change), 'key2': next(change), 'key3': next(change), 'key4': 10010 } print(changing_dict) # Output # {'key1': 100, 'key2': 105, 'key3': 110, 'key4': 10010} pri...
piyush daga
1

votes
3

answer
58

Views

Select element in list of values in dictionary

I have a dictionary with the values being list with 2 or more elements. I want to slice in those values with more than 2 elements based on the other values with only 2 elements in their list. I know i can append all the value elements to a list and then just count the most common, but i need to kee...
RAHenriksen
1

votes
2

answer
39

Views

Display list elements using index of dictionary in Jinja(Django)

I'm using Django Version 2.1.7,jinja2 and i trying to iterate list inside a dictionary using forloop.counter0 in Jinja template. MyCode Views.py : def sample(request): datas= ['value1','value2','value3'] #list data={'key1':'val1','key2':'val2','key3':'val3'} #dictionary return render(request,'inde...
Abhijith
1

votes
3

answer
27

Views

Python append to return dict instead of a list

The append below is working but it is return a list instead of a dict. So when I tried the extract the key/value with tag.items() it is telling me that there's a ValueError: not enough values to unpack (expect 2, got 1) This is the correct error message as it a list as all_tags.append creates a lis...
munchine
1

votes
2

answer
51

Views

Looping through a python dictionary and manipulate each value

I am a fairly new python user and I am stuck on a problem. Any guidance would be greatly appreciated. I have a pandas data frame with three columns 'ID', 'Intervention', and 'GradeLevel'. See code below: data = [[100,'Long', 0], [101,'Short', 1],[102,'Medium', 2],[103,'Long', 0],[104,'Short', 1],[...
Jake
1

votes
2

answer
59

Views

Remove the smallest N values from python dictionary

Suppose that I have the following dictionary: d = {'q' : 2, 'b': 22, 'c': 19, 'e': 3, 'd': 9} What I want to do is to iteratively remove the smallest values (with their keys) from the dictionary. For instance, if I want to remove 2 smallest values, I expect to obtain the following as remaining dicti...
inverted_index
1

votes
3

answer
61

Views

Remove duplicate values from list of nested dictionaries

I have list of dictionaries with nested structure. I need to remove all duplicate values. I'm newbie in Python and can't solve this task. Anyone can help me? My list looks like: [ { 'task_id':123, 'results':[ { 'url':'site.com', 'date':'04.18.2019' }, { 'url':'another_site.com', 'date':'0...
Nataly Firstova
1

votes
3

answer
44

Views

How to Write a Python program to find smallest and largest word in a given string?

I am trying to find the largest and smallest word in a given string. This is my target string. 'Hello, welcome to python programming ' I have extracted the words in the string and their lengths into key value pairs in a dictionary. Below is the code i wrote. Line='Hello, welcome to python programm...
Patronus X24
1

votes
5

answer
60

Views

Iterate in O(n^2 / 2) a dict

Given a dictionary : d = {'a':0, 'b': 1, 'c': 2} I would like to make a new dictionary that computes the product of values of d and d. This is the result I need : d = {'a#a': 0, 'a#b': 0, 'a#c': 0, 'b#b' : 1, 'b#c': 2, 'c#c': 4} However I do not want to have this result : d = {'a#a': 0, 'a#b': 0, '...
truvaking
2

votes
3

answer
31

Views

Convert DataTable into a Dictionary using Linq/Lambda

I have a DataTable that I would like to convert into dictionary in C# for my project. I can use the traditional way of programming to achieve the goal but it is not as elegant as using linq/lambda. I tried to use Lambda but I got stuck in how to flatten multiple rows into 1. I have a mock DataTable...
user1205746
0

votes
0

answer
12

Views

How to create a dynamic nested json that can be stored and reloaded and edited afterwards in python?

I want to provide templates that can later be edited by a user. Therefore, it should be a human-readable .json object. Example of a template containing only one field: {'template_name': 'sample_name', 'attribute_fields': [{'attribute_name': 'banana', 'attribute_tags': ['chiquita', 'pinkylady'], 'at...
kalsari
1

votes
3

answer
21

Views

Compare lists of dictionaries based on values

I have two lists of dictionaries as: old_data = [{'company': 'Amazon', 'logged_in': '2019-01-20'}, {'company': 'Facebook', 'logged_in': '2019-04-20'}, {'company': 'Google', 'logged_in': '2019-04-20'}] new_data = [{'company': 'Amazon', 'logged_in': '2019-01-26'}, {'company': 'Facebook', 'logged_in':...
Gokul
0

votes
0

answer
16

Views

Is parsing Array of Dictionary possible in Parse?

I am using parse server (It's my first time using parse) for retrieving data and saving. I am stuck at a point where I have searched the Web for parsing the JSON response where it is an Array of Dictionaries. Please have a look at the below JSON {'delivery_hours':[{'day':'Monday','open':{'hour':'11...
iDeveloper
11

votes
5

answer
434

Views

Using a map function on a 'Map' to change values

I can use a Map and then set values: const a = new Map([['a', 'b'], ['c', 'd']]) Now if I want to apply a function to all values in a functional way (without for ... of or .forEach), I thought I could have done something like this: const b = a.map(([k, v]) => [k, doSomethingWith(v)]); But there is n...
rap-2-h
0

votes
2

answer
23

Views

In Python, how do I read an input file to then translate it to morse code?

I have to create a program that asks the user for an input file, and then creates an output file containing the message encoded in Morse code. When I run my program, there's a type error in the 'translated += alphabet[words]' line, it says it's an unhashable type: 'list'. How can I translate the tex...
user11407982
0

votes
0

answer
14

Views

ADDING keys and value from a dictionnary to a csv file and filtered values of a dictionnary in python

I would like to add key and values of my dictionary : d_tag to my file csv starting from the third column , I tried a lot of solution but it doesnt work I have the Following error : Traceback (most recent call last): File 'CSV_dico.py', line 62, in writer.writerow(k) File 'C:\Users\Emmanuelle\A...
kely789456123
0

votes
0

answer
10

Views

How do you convert JSON in VB.net for consumption in PHP

I was handed a php file that submits a JSON String to an API. The application I am working with to do the same, however, runs on VB.net. I have used a Dictionary object to reconstruct the JSON object but I am getting some subtle differences in final output. Here is my code: Dim data As New Dictionar...
Hannington Mambo
0

votes
0

answer
9

Views

Separating dictionaries

I'm fairly new to python programming and am currently working on dataquest's data science path. I'm stumped on their separating dictionaries assignment. If anybody can explain step by step what to do or show me some outside resources I would appreciate it. This is the problem: Previously, we transfo...
user11385063
-4

votes
0

answer
37

Views

Efficient way to check if a string contains any of the keys in a dictionary

I have a map that stores the mapping between a keyword and a topic. If a title of a book contains any of the keywords in the map, it should be assigned the corresponding topic. Below is a simplified example of maps and titles. Example map key_topic: keyword1, topic1 keyword2, topic1 keyword3, topic...
kami
1

votes
1

answer
24

Views

Is there a way to enumerate a list or dictionary that share the same index?

I want to enumerate a list or dictionary, if the items share the same value or are equal I want them to use 1 index. This is my code: def print_data(league_results): for i, (team, points) in enumerate(sorted(league_results.items(), key=lambda x: x[1], reverse=True), 1): if points == 1: i = i print...
Thando
1

votes
2

answer
183

Views

How to call to an Umbraco dictionary item in XSLT?

I'm working on an Umbraco site which mostly uses .cshtml files, but for a couple small places, they use .xslt files to handle embedding videos. I don't know a thing about .xslt. But, through my googling, I've figured out what I need to put to call to a dictionary item (which will replace hard-coded...
Stacy K. Basye
1

votes
1

answer
4.5k

Views

How to check whether a item (not the key) exists in the dictionary VBA

I would like to check whether a specific value exists in a dictionary. I have created a dictionary as such: Set Curr = CreateObject('Scripting.Dictionary') For Index = 1 To NoOfCurr Curr.Add Index, Cells(15 + Index, 5).Value Next I need to check whether a string exists in the dictionary. I have writ...
lakesh

View additional questions