I trying to make this code work:
civil_freq= { '430.00': ['aaa'],
'430.02': ['aaa'],
'430.04': ['aaa'],
'430.06': ['bbb'],
'430.08': ['bbb'],
'430.10': ['bbb'],
'430.12': ['none'],
'430.14': ['none']}
person_freq=[]
person = 'bbb'
for key in civil_freq:
if civil_freq[key] == person:
person_freq.append(civil_freq.get(key))
print(person_freq)
it return empty list, but I need smth like
['430.06', '430.08', '430.10']
Issue: You're storing the persons names in a list (within your civil_freq dictionary) but comparing it with a string (variable person). This comparison won't work.
Try this:
person = ["bbb"]
for k, v in civil_freq.items():
if v == person:
person_freq.append(k)
print(person_freq)
or change the values within your dictionary from lists to strings!
Related
My dict (cpc_docs) has a structure like
{
sym1:[app1, app2, app3],
sym2:[app1, app6, app56, app89],
sym3:[app3, app887]
}
My dict has 15K keys and they are unique strings. Values for each key are a list of app numbers and they can appear as values for more than one key.
I've looked here [Python: Best Way to Exchange Keys with Values in a Dictionary?, but since my value is a list, i get an error unhashable type: list
I've tried the following methods:
res = dict((v,k) for k,v in cpc_docs.items())
for x,y in cpc_docs.items():
res.setdefault(y,[]).append(x)
new_dict = dict (zip(cpc_docs.values(),cpc_docs.keys()))
None of these work of course since my values are lists.
I want each unique element from the value lists and all of its keys as a list.
Something like this:
{
app1:[sym1, sym2]
app2:[sym1]
app3:[sym1, sym3]
app6:[sym2]
app56:[sym2]
app89:[sym2]
app887:[sym3]
}
A bonus would be to order the new dict based on the len of each value list. So like:
{
app1:[sym1, sym2]
app3:[sym1, sym3]
app2:[sym1]
app6:[sym2]
app56:[sym2]
app89:[sym2]
app887:[sym3]
}
Your setdefault code is almost there, you just need an extra loop over the lists of values:
res = {}
for k, lst in cpc_docs.items():
for v in lst:
res.setdefault(v, []).append(k)
First create a list of key, value tuples
new_list=[]
for k,v in cpc_docs.items():
for i in range(len(v)):
new_list.append((k,v[i]))
Then for each tuple in the list, add the key if it isn't in the dict and append the
doc_cpc = defaultdict(set)
for tup in cpc_doc_list:
doc_cpc[tup[1]].add(tup[0])
Probably many better ways, but this works.
I have an array that contains details about a form grabbed in open XML. The key format is funky which is why i am having trouble getting the values easily. A simple loop for key, value pairs does not return the data i want. Here is where i am currently at, i am using python3.
person = [{'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val': 'Title'}, {'http://schemas.openxmlformats.org/wordprocessingml/2006/main}val': 'FirstName'}, {'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val': 'LastName'},{'{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val': 'Age'}]
for k in person:
print(k.values())
returns
dict_values(['Title'])
dict_values(['FirstName'])
dict_values(['LastName'])
dict_values(['Age'])
How can i parse these key:value pairs so that i don't get dict_values in front of the value.
Desired output looks like this:
Title
FirstName
LastName
Age
And if i do this:
for k in person:
for key, value in k:
print(v)
I get returned an error of too many values to unpack, which there is only 2 so i dont understand what the error is. Length is 1 when ran on an individual object
You have a rather inefficient format here. You have a list with dictionaries, each with just one key-value pair in them. Things would have been a bit better if your code would instead produce a single dictionary with all those key-value pairs in one object.
You are now printing the .values() dictionary view object. Each contains just one value. You could loop over the object and print each value of each view:
for k in person:
for value in values():
print(value)
Or you could merge all the dictionaries into one and then just loop directly over the values of that single dictionary:
combined = dict(item for d in person for item in d.items())
for value in combined.values():
print(value)
I have the a dictionary within a list
[{'123': 'some text'}]
I want my output to be a string with the keys and values separated like so
'123', 'some text'
Any suggestions?
Try this:
my_list_dict = [{'123': 'some text'}]
for elem in my_list_dict:
for key in elem:
print('key:', key)
print('value:', elem[key])
I think you want the values into the list, right?
Here is my aprouch
list_dict = [{'123': 'some text'}]
list_without_dict = []
for dict in list_dict:
for key in dict:
list_without_dict.append(key)
list_without_dict.append(dict[key])
print(list_without_dict)
simply iterate over the whole of your input keeping the keys and values and use ', '.join() to join a list into a string with ", " as a delimiter
wierd_input = [{'123': 'some text', 'foo':'boo'}, {'and':'another'}]
all_parts = []
for dictionary in wierd_input:
for key, value in dictionary.items():
all_parts.extend((key, value))
print(", ".join(all_parts))
>>123, some text, foo, boo, and, another
you can convert this into a generator if you want to join such objects frequently in your code
def iterate_over_wierd(wierd):
for dictionary in wierd:
for key, value in dictionary.items():
yield key
yield value
print(", ".join(iterate_over_wierd(wierd_input)))
if you desperately need a one-liner you can use itertools
import itertools
', '.join(itertools.chain.from_iterable(itertools.chain.from_iterable(map(dict.items,wierd_input))))
but I advise against this as the one liner is very confusing and hacky, better stick to the former two
I have an Object in Groovy like:
class Person {
def name
def age
}
And a collection of persons stored in a map:
Person a = new Person(name: 'A', age:29)
Person b = new Person(name: 'B', age:15)
Map persons = ['1':a, '2':b]
I'm trying to update the age field for all persons, I know that I can do something like:
persons.each{ k,v -> v.age=0 }
But, I was wondering if is there another way to do it without iterating the entire map. As you can see, all persons should have the same value
You can use the spread operator:
persons.values()*.age = 0
I have a record as
["name1":["value1":10, "value2":name1, "value3":150, "value4":20],
"name2":["value1":10, "value2":name2, "value3":150, "value4":20]]
I have a list where the values are name1, name2, etc.
I want to pull the list depending on the name1 as
["name1":["value1":10, "value2":name1, "value3":150, "value4":20]]
.subMap(["name1"]) did work for me, but I have a list and by looping the list I need to pull the values
Ex : namesList.each{record ->
newMap = firstmap.subMap(record)
}
Use subMap(Collection keys):
def map = ["name1":["value1":10, "value2":"name1", "value3":150, "value4":20],
"name2":["value1":10, "value2":"name2", "value3":150, "value4":20]]
//Answer here, return Map still:
println map.subMap("name1")
//Or
println map.subMap(["name1", "name2"])